【问题标题】:How to take specific elements on multiple lists on beautifulsoup?如何在 Beautifulsoup 的多个列表中获取特定元素?
【发布时间】:2019-07-10 13:05:43
【问题描述】:

我无法提取一些特定标签(及其字符串内容)并将它们存储到变量中(这样我以后可以将这些变量放入 CSV 文件中)。

from bs4 import BeautifulSoup
from requests_html import HTMLSession
session = HTMLSession()
r = session.get('https://www.khanacademy.org/profile/DFletcher1990/')
r.html.render(sleep=5)
soup=BeautifulSoup(r.html.html,'html.parser')

user_info_table=soup.find('table', class_='user-statistics-table')

for tr in user_info_table.find_all('tr'):
    tds=tr.find_all('td')
    print(tds)

我要收藏:

  • "4 years ago" 并将其存储到一个名为 date 的变量中,
  • "932,915" 并将其存储到一个名为 points 的变量中,
  • "372" 并将其存储到名为 videos 的变量中。

我不太明白bs4.element.ResultSet 的行为...

【问题讨论】:

    标签: python-3.x web-scraping beautifulsoup html-parsing


    【解决方案1】:

    你可以把它当作一个列表。

    from bs4 import BeautifulSoup
    from requests_html import HTMLSession
    session = HTMLSession()
    r = session.get('https://www.khanacademy.org/profile/DFletcher1990/')
    r.html.render(sleep=10)
    soup=BeautifulSoup(r.html.html,'html.parser')
    user_info_table=soup.find('table', class_='user-statistics-table')
    dates,points,videos=[tr.find_all('td')[1].text for tr in user_info_table.find_all('tr')]
    print(dates,points,videos,sep="\n")
    

    输出

    4 years ago
    932,915
    372
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-05
      • 1970-01-01
      • 2014-02-13
      • 1970-01-01
      • 2021-08-03
      相关资源
      最近更新 更多