【发布时间】:2019-07-01 17:23:29
【问题描述】:
我正在尝试从此链接中抓取网页,https://www.premierleague.com/stats/top/players/goals?se=-1 而且我似乎没有成功。
下面是我试过的代码。
from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
import csv`
url = "https://www.premierleague.com/stats/top/players/goals?se=-1"
html = urlopen(url)
bs = BeautifulSoup(html, 'html.parser')
#print(bs)
listings = []
for rows in bs.find_all("tr"):
if("oddrow" in rows["class"]) or ("evenrow" in rows["class"]):
name = rows.find("div", class_="playerName").a.get_text()
country = rows.find_all("td")[1].get_text()
goals = rows.find_all("td")[4].get_text()
listings.append([name, country, goals])
with open("EPL_TEST.csv", 'a', encoding = 'utf-8') as toWrite:
writer = csv.writer(toWrite)
writer.writerows(listings)
print("Data Fetched")
这是我得到的错误:C:\Users\Siddhardh\Desktop\Python\Projects\FinalProject\venv\Scripts\python.exe C:/Users/Siddhardh/Desktop/Python/Projects/FinalProject/Scraping.py
Traceback (most recent call last): File "C:/Users/Siddhardh/Desktop/Python/Projects/FinalProject/Scraping.py", line 16, in <module>
if("oddrow" in rows["class"]) or ("evenrow" in rows["class"]): File "C:\Users\Siddhardh\Desktop\Python\Projects\FinalProject\venv\lib\site-packages\bs4\element.py", line 1016, in __getitem__ return self.attrs[key] KeyError: 'class'
Process finished with exit code 1
我需要将所有球员的姓名、国家和目标放入 CSV 文件中。
附:请原谅我的编辑技巧。这是我在这里的第一篇文章。我会学习的。
【问题讨论】:
-
您查看过@Siddarth Krishna S 的任何一个答案吗?人们花时间解决问题,所以尽量不要无动于衷。谢谢。
-
对不起。是的,人们一直乐于助人。我刚出城,没有带笔记本电脑。刚回来看看这些 cmets。
标签: python web-scraping