【问题标题】:Locating table with no id or class attributes定位没有 id 或 class 属性的表
【发布时间】:2016-06-14 17:22:54
【问题描述】:

我正在尝试用几张桌子抓取一个网站。两个表都没有类或 id,并且该站点确实不使用任何一个,所以我不确定是否有办法让我获取数据。 这是该网站的链接 - 我会发布 html,但它会太长。

http://epi.hbsna.com/products/dept.asp?msi=0&sid=6076533CE8C648AE9883BDDBED795B29&dept_id=315&parent_id=0

我要提取的表从第 310 行开始。

【问题讨论】:

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


    【解决方案1】:

    由于这是BeautifulSoup 的具体问题,因此这是一个有效的BeautifulSoup 特定解决方案。这个想法是找到具有SKU# 文本和locate the first table parent 的元素:

    import requests
    from bs4 import BeautifulSoup
    
    
    data = requests.get('http://epi.hbsna.com/products/dept.asp?msi=0&sid=6076533CE8C648AE9883BDDBED795B29&dept_id=315&parent_id=0').content
    soup = BeautifulSoup(data, "html.parser")
    
    table = soup.find(text="SKU#").find_parent("table")
    for row in table.find_all("tr")[1:]:
        print([cell.get_text(strip=True) for cell in row.find_all("td")])
    

    打印表格的内容:

    ['40010001', 'ABA Service Kit', '-', '1-1/4" 10', 'None', '5-1/2"', '0.63', 'Clamp', '42710566']
    ['40010002', 'ABA Service Kit', '-', '1-1/4" 10', '5/8" RH', '5-1/2"', '0.63', 'Clamp', '42710566']
    ...
    ['40010649', 'ABA Service Kit', '-', '1 1/2 - 10', '1.5', '6"', '0.50', 'Strap', '427-10517']
    ['40050604', 'ABA Service Kit', 'none', '1 1/2" - 10"', '1 1/2" LH', '6"', '0.50', 'Strap', '427-10601']
    

    【讨论】:

    • 谢谢 - 看起来很完美 - 此代码是否适用于 3.5 - 我遇到了一些错误
    • @PatrickP76 是的,在 3.5 上测试过。你得到什么错误?谢谢。
    • 别担心 - 我能弄明白 - 你是最好的 - 我只需要将请求更改为 3.5 版本
    【解决方案2】:

    您对使用这个xpath 表达式感觉如何?

    //*[./text()="SKU#"]/ancestor::table[1]
    

    意思是,“找到第一个文本正好是 SKU# 的元素,然后选择它最近的表祖先。”

    您可以通过将表达式作为字符串传递给$x 函数,在浏览器检查器中进行尝试。


    请参阅 this answer 以在 beautifulsoup 中使用 xpath

    【讨论】:

    • 如果存在 SKU# 会出现在文档其他位置的风险,您可以选择始终只出现在表格中的任何其他文本位。
    • 我是新手,还没有尝试过甚至听说过 xpath - 我会研究并希望能做到这一点。谢谢。
    • @alecxe 的答案非常适合仅使用beautifulsoup,而且读起来非常清楚! xpath 是一种用于导航 xml 文档的语言,它在大多数编程语言中都有实现。作为您的网络抓取工具包的一部分,值得一试。 :)
    猜你喜欢
    • 1970-01-01
    • 2014-01-08
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    相关资源
    最近更新 更多