Python crawler results save txt file

This article is only used as a code record

#!/usr/bin/python
# -*- coding: UTF-8 -*-    
# Author: RuiMing Lin
# DateTime: 2021/01/25 14:49
# Description:
import requests
from pyquery import PyQuery as pq

'''
r:以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
rb:以二进制只读方式打开一个文件。文件指针将会放在文件的开头。
r+:以读写方式打开一个文件。文件指针将会放在文件的开头。
rb+:以二进制读写方式打开一个文件。文件指针将会放在文件的开头。
w:以写入方式打开一个文件。如果该文件已存在,则将其覆盖。如果该文件不存在,则创建新文件。
wb:以二进制写入方式打开一个文件。如果该文件已存在,则将其覆盖。如果该文件不存在,则创建新文件。
w+:以读写方式打开一个文件。如果该文件已存在,则将其覆盖。如果该文件不存在,则创建新文件。
wb+:以二进制读写格式打开一个文件。如果该文件已存在,则将其覆盖。如果该文件不存在,则创建新文件。
a:以追加方式打开一个文件。如果该文件已存在,文件指针将会放在文件结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,则创建新文件来写入。
ab:以二进制追加方式打开一个文件。如果该文件已存在,则文件指针将会放在文件结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,则创建新文件来写入。
a+:以读写方式打开一个文件。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,则创建新文件来读写。
ab+:以二进制追加方式打开一个文件。如果该文件已存在,则文件指针将会放在文件结尾。如果该文件不存在,则创建新文件用于读写。
'''


# 爬取页面的方法
def get_html(page):
    url = "https://nba.hupu.com/stats/players/pts/" + str(page)
    response = requests.get(url=url)
    if response.status_code == 200:
        return response.text
    else:
        return None


def scrape_html_1(i):
    html = get_html(i)
    doc = pq(html)
    trs = doc.find("table tr:not(:first-child)").items()
    file = open('files/hupu.txt', 'a+', encoding='utf-8')  # 打开文件,以追加文件的方式
    for tr in trs:
        name = tr.find("td:nth-child(2)").text()
        team = tr.find("td:nth-child(3)").text()
        score = tr.find("td:nth-child(4)").text()
        rate = tr.find("td:nth-child(6)").text()
        file.write(name + '\t' + team + '\t' + score + '\t' + rate + '\n')
    file.close()


def scrape_html_2(i):
    html = get_html(i)
    doc = pq(html)
    trs = doc.find("table tr:not(:first-child)").items()
    for tr in trs:
        name = tr.find("td:nth-child(2)").text()
        team = tr.find("td:nth-child(3)").text()
        score = tr.find("td:nth-child(4)").text()
        rate = tr.find("td:nth-child(6)").text()
        with open('files/hupu.txt', 'a+', encoding='utf-8') as file:  # 文件操作简化方式,引入局部变量file,不需要手动释放
            file.write(name + '\t' + team + '\t' + score + '\t' + rate + '\n')


if __name__ == '__main__':
    for i in range(3):
        # scrape_html_1(i + 1)
        scrape_html_2(i + 1)

Guess you like

Origin blog.csdn.net/Orange_minger/article/details/113475557