【问题标题】:NoneType' object has no attribute 'find_all' error comingNoneType' 对象没有属性 'find_all' 错误来了
【发布时间】:2021-12-15 04:04:47
【问题描述】:

我正在使用 Beautiful Soup 抓取维基百科表格 这是我的代码

代码

URL="https://en.wikipedia.org/wiki/List_of_most-viewed_YouTube_videos"  
page=requests.get(URL)    
soup1=BeautifulSoup(page.text,'lxml')   
table = soup1.find('table',{'class':'wikitable sortable jquery-tablesorter'})    

headers=[]
for i in table.find_all('tr'):    
    title=i.text.strip()    
    headers.append(title)

我得到了错误

AttributeError: 'NoneType' object has no attribute 'find_all'

我尝试使用 htmlparserget_text 函数仍然得到同样的错误,即使 th 也出现同样的错误。

【问题讨论】:

    标签: python pandas beautifulsoup


    【解决方案1】:

    你可以只使用 pandas 来做到这一点

    import pandas as pd
     
    table = pd.read_html("https://en.wikipedia.org/wiki/List_of_most-viewed_YouTube_videos",attrs={'class':'wikitable sortable'})[0] 
    print(table)   
    

    【讨论】:

    • 好的,但事情是我的任务是网络报废此页面,所以我需要网络报废该表格,我给出的 x 路径是正确的,但我没有得到它
    • 当我尝试你的代码时,我得到了 ValueError: No tables found
    • 再试一次,我已经更新了
    • 是的,谢谢
    【解决方案2】:

    如何查找标题:

    进入 chrome 开发者模式并重新加载您的网站并转到主 url 并找到标题选项卡,其中将列出所有与数据相关的 URL

    使用bs4,您必须添加user-agent 才能从HTML 中获取数据,然后table 标签返回所有值

    import requests
    from bs4 import BeautifulSoup
    headers={"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36"}
    response = requests.get('https://en.wikipedia.org/wiki/List_of_most-viewed_YouTube_videos',headers=headers)
    
    soup = BeautifulSoup(response.text,'html.parser')
    table = soup.find('table',attrs={"class":"wikitable sortable"})
    headers=[]
    for i in table.find_all('tr'):    
        title=i.text.strip()    
        headers.append(title)
    

    这里是使用pandas的实现:

    import pandas as pd
    
    data=pd.read_html(response.text,attrs={"class":"wikitable sortable"})
    

    【讨论】:

      猜你喜欢
      • 2022-01-12
      • 2014-06-04
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-17
      相关资源
      最近更新 更多