This article is only used as a code record
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Author: RuiMing Lin
# DateTime: 2021/01/25 14:51
# Description:
import requests
from pyquery import PyQuery as pq
import csv
import numpy
import pandas as pd
'''
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()
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()
yield [name, team, score, rate]
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()
yield {
'名字': name,
'队伍': team,
'得分': score,
'命中率': rate
}
# 写入列表,逐行写入
flag = False
# flag = True
if flag:
results = []
for i in range(3):
results.extend(scrape_html_1(i + 1))
with open('files/data.csv', 'w', encoding='utf-8', newline='') as file:
for result in results:
writer = csv.writer(file)
writer.writerow(result)
# 写入列表,多行写入
flag = False
# flag = True
if flag:
results = []
for i in range(3):
results.extend(scrape_html_1(i + 1))
with open('files/data.csv', 'w', encoding='utf-8', newline='') as file:
writer = csv.writer(file)
writer.writerows(results)
# 写入字典
flag = False
# flag = True
if flag:
results = []
for i in range(3):
results.extend(scrape_html_2(i + 1))
with open('files/data.csv', 'w', encoding='utf-8', newline='') as file:
fieldnames = ['名字', '队伍', '得分', '命中率']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(results)
# 读取本地csv文件
flag = False
# flag = True
if flag:
with open('files/data.csv', 'r', encoding='utf-8') as file:
reader = csv.reader(file)
for row in reader:
print(type(row))
print(row)
# 使用pandas的read_csv()
flag = False
flag = True
if flag:
df = pd.read_csv('files/data.csv')
print(df)