找不到id或class属性的表

时间:2016-03-02 02:32:11

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

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

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

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

2 个答案:

答案 0 :(得分:3)

由于这是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']

答案 1 :(得分:2)

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

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

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

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

请参阅this answer,了解如何使用xpath中的beautifulsoup