【问题标题】:How to scrape the website properly and getting all td texts from website如何正确抓取网站并从网站获取所有 td 文本
【发布时间】:2021-02-15 21:13:35
【问题描述】:

我是 python 新手。有谁知道 {sum(int(td.text) for td in soup.select('td:last-child')[1:])} 在 this 或 [0] 或 [1] 中 [1:] 的用途是什么]。我在下面的 for in 循环中的许多抓取示例中看到了它。当我练习时,我构建了这段代码并且无法抓取 csv 文件中的所有数据。提前致谢,很抱歉一次有两个问题。

import requests
from bs4 import BeautifulSoup
import csv

url= "https://iplt20.com/stats/2020/most-runs"

r= requests.get (url)

soup= BeautifulSoup (r.content, 'html5lib')

lst= []

table=soup.find ('div', attrs = {'class':'js-table'})



#for row in table.findAll ('div', attrs= {'class':'top-players__player-name'}):
#    score = {}
 #   score['Player'] = row.a.text.strip()
#    lst.append(score)

for row in table.findAll (class_='top-players__m top-players__padded '):
    score = {}
    score['Matches'] = int(row.td.text)
    lst.append(score)

filename= 'iplStat.csv'
with open (filename, 'w', newline='') as f:
    w= csv.DictWriter(f,['Player', 'Matches'])
    w.writeheader()
    for score in lst:
        w.writerow(score)



print (lst)

【问题讨论】:

  • 如果我的回答对你有帮助,请接受我的回答作为最好的回答。谢谢!
  • 您所要做的就是单击我的答案附近的绿色刻度线。接受一个答案作为最佳答案将使网站保持清洁,还可以帮助您获得 2 点声望!!!
  • 完成。但是你能建议如何学习编码编码吗?
  • 看几个教程,解决更多练习。

标签: python web web-scraping beautifulsoup python-requests


【解决方案1】:

甚至不需要所有这些。只需使用pandas:

import requests
import pandas as pd

url = "https://iplt20.com/stats/2020/most-runs"

r = requests.get (url)

df = pd.read_html(r.content)[0]

df.to_csv("iplStats.csv", index = False)

csv 文件截图:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 2018-01-09
    • 2021-11-17
    • 1970-01-01
    • 2011-09-19
    • 2019-04-23
    相关资源
    最近更新 更多