【问题标题】:HTML table scraping in python - trouble finding tables on some pagespython中的HTML表格抓取-在某些页面上查找表格时遇到问题
【发布时间】:2020-07-22 14:14:07
【问题描述】:

我正在尝试从该网站的价格表中抓取数据:https://www.letsrecycle.com/prices/textiles/textile-prices-2012/

我无法同时使用 read_html 和 BeautifulSoup 找到表格,这很奇怪,因为我能够在其他类似页面上找到表格(例如 https://www.letsrecycle.com/prices/metals/steel-cans/steel-can-prices-2018/

我尝试过使用不同的解析器,但这并没有帮助。我的代码的相关部分如下:

import pandas as pd
import html5lib
import requests
from bs4 import BeautifulSoup
import urllib    
url = 'http://www.letsrecycle.com/prices/textiles/textiles-prices-2012'
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
webpage = urlopen(req).read()
dfs = pd.read_html(webpage)

我还尝试了各种 BeautifulSoup 解析器,例如:

soup = BeautifulSoup(webpage, "html5lib")
table = soup.findAll("table")
table

提前非常感谢

【问题讨论】:

    标签: python html web-scraping beautifulsoup


    【解决方案1】:

    你需要标题:

    import requests
    import pandas as pd
    
    headers = {'User-Agent':'Mozilla/5.0'}
    r = requests.get('https://www.letsrecycle.com/prices/textiles/textile-prices-2012/', headers=headers)
    dfs = pd.read_html(r.text)
    print(dfs)
    

    输出:

    [                  0          1          2  ...          4          5          6
    0              2012    January   February  ...      April        May       June
    1     Textile banks  270 - 340  260 - 350  ...  260 - 360  260 - 360  260 - 350
    2  Shop collections  490 - 550  500 - 560  ...  500 - 560  500 - 570  510 - 580
    3      Charity rags  580 - 650  600 - 670  ...  610 - 700  620 - 700  620 - 720
    
    [4 rows x 7 columns],                   0          1          2  ...          4          5          6
    0              2012       July     August  ...    October   November   December
    1     Textile banks  250 - 350  250 - 330  ...  260 - 340  260 - 340  250 - 340
    2  Shop collections  520 - 590  530 - 590  ...  530 - 580  540 - 590  530 - 580
    3      Charity rags  630 - 730  640 - 740  ...  650 - 730  650 - 730  640 - 730
    
    [4 rows x 7 columns]]
    

    【讨论】:

    • 您好,感谢您的帮助。恐怕我逐字尝试了您的代码,但仍然出现错误(ValueError:未找到表)-这与我遇到的错误相同。
    • 奇怪,因为没有标题我也会得到 ValueError 但有了标题它就像一个魅力。 @stormcrow03
    【解决方案2】:

    我发现了问题 - 这是一个不一致的 URL。 例如。 2006 年的 URL 是: https://www.letsrecycle.com/prices/textiles/textiles-prices-2006/ (纺织品/纺织品 - 带有“s”)

    但 2012 年的 URL 是: https://www.letsrecycle.com/prices/textiles/textile-prices-2012/ (纺织品/纺织品 - 没有's')

    这就是我的代码找不到任何表的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-27
      • 2019-02-19
      • 1970-01-01
      • 2021-07-25
      • 2017-07-07
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      相关资源
      最近更新 更多