【问题标题】:extracting content from 1 column of table with beautiful soup用漂亮的汤从一列表格中提取内容
【发布时间】:2023-04-06 03:19:01
【问题描述】:

我是网络抓取的新手,我正在尝试从该网站提取所有期刊的所有名称:https://ideas.repec.org/top/top.journals.simple.html

这是我目前的尝试(按照这里的教程https://www.pluralsight.com/guides/extracting-data-html-beautifulsoup):

import requests
from bs4 import BeautifulSoup

URL = "https://ideas.repec.org/top/top.journals.simple.html"
html_content = requests.get(URL).text
soup = BeautifulSoup(html_content, "lxml"

journal_list = soup.find("table", attrs={"class": "toplist"})
journal_list_data = journal_list.tbody.find_all("tr")

headings = []

for td in journal_list_data[0].find_all("td"):
     headings.append(td.b.text.replace('\n', '').strip())

print(headings)

这只是为了获取表格标题的列表,然后我会尝试从“期刊”列中提取所有期刊名称,但我得到一个 AttributeError 基本上说 journal_list.tbody 是 NoneType,当我检查 journal_list.attrs 时,它只给出 {'class': 'toplist'),即使页面上的 HTML 肯定有一个 tbody 属性。

我做错了什么/还有其他更好的方法吗?

谢谢!

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

    会发生什么?

    首先看看你的汤,有你的真相 - 没有

    <tbody> 也没有<b> 可以从中获取信息。这就是你以错误结束的原因。

    试试这个

    import requests
    from bs4 import BeautifulSoup
    
    URL = "https://ideas.repec.org/top/top.journals.simple.html"
    html_content = requests.get(URL).text
    soup = BeautifulSoup(html_content, "lxml")
    
    journal_list = soup.find("table", attrs={"class": "toplist"})
    journal_list_data = journal_list.find_all("tr")
    
    headings = []
    
    for td in journal_list_data[0].find_all("td"):
         headings.append(td.text.replace('\n', '').strip())
    
    print(headings)
    

    替代get_text()

    您也可以使用get_text() 来抓取和剥离元素的文本:

    headings.append(td.get_text(strip=True))
    

    解决方案 - 表格的一列

    仅从一列中获取 text,例如你可以做以下日记:

    [journal.find_all("td")[1].get_text(strip=True) for journal in journal_list_data[1:]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 2017-10-05
      • 2015-08-07
      相关资源
      最近更新 更多