【问题标题】:How to scrape information inside an unordered list selenium + python如何在无序列表 selenium + python 中抓取信息
【发布时间】:2020-06-05 18:21:57
【问题描述】:

我正在做一个网络抓取项目,我试图从亚马逊网站上抓取信息。在网站中,存在一个包含此类信息的无序列表

Item Weight: 17.2 pounds
Shipping Weight: 17.4 pounds (View shipping rates and policies)
ASIN: B00HC767P6
UPC: 766789717088 885720483186 052000201628
Item model number: mark-1hooi-toop842
Customer Reviews: 4.8 out of 5 stars1,352 customer ratings
Amazon Best Sellers Rank: #514 in Grocery & Gourmet Food (See Top 100 in Grocery & Gourmet Food)
#12 in Sports Drinks

列表本身没有任何类别。问题是我不想要列表中的所有信息。只有 ASIN 码。 li 标签没有任何特定的类或 ID。这是product details page的链接

在使用 selenium 之前,我使用的是 BeautifulSoup,这就是我解决问题的方式

asin = str(soup.find('bdi', {'dir': 'ltr'}).find_parent('li'))[38:].split('<')[0]

我现在改用 selenium。如何抓取信息。

【问题讨论】:

    标签: python selenium web-scraping beautifulsoup


    【解决方案1】:

    您可以使用 css 选择器获取相关的 li 项,如下所示:

    通过css选择器按索引查找子元素

    $(".content > ul > li:nth-child(2)").textContent >>> "Shipping Weight: 33 pounds (View shipping rates and policies)"
    $(".content > ul > li:nth-child(3)").textContent >>> "ASIN: B07QKN2ZT9"
    

    相关python selenium代码:

    driver.find_element_by_css_selector(".content > ul > li:nth-child(3)").text.split(": ")[1] >>> 'B07QKN2ZT9'
    

    通过 XPATH 查找祖先元素

    如果 ASIN 并不总是在同一个索引中,那么您可以找到具有文本 ASIN 文本的 bdi 元素并找到其 ancestor::li,然后获取其文本并提取相关部分。像下面这样:

    driver.find_element_by_xpath("//bdi[text()='ASIN']/ancestor::li").text.split(": ")[1] >>> 'B07QKN2ZT9'
    

    生成 XPATH

    //<element type>[<attribute type> = <attribute value>]/<descendant>
    //bdi[text() = 'ASIN'] >>> bdi element with text 'ASIN'
    //bdi[@dir = 'ltr'] >>> bdi element with dir attribute equals to 'ltr'
    

    访问元素的祖先

    /ancestor::<ancestor element type>
    //bdi[text()='ASIN']/ancestor::li >>> li
    //bdi[text()='ASIN']/ancestor::ul >>> ul
    

    您可以查看this as a reference

    【讨论】:

    • 嗨。尽管此答案有效,但 asin 字段可能并不总是列表中的第三个元素。这就是问题所在。有时它也可能是第二个元素,有时是第四个元素。在所有情况下,我都只需要访问该字段...
    • @Sashaank 这个没有被提及但是更新了你可以查看的解决方案
    • 非常感谢。这段代码就像一个魅力。我现在必须开始更正确地学习 xpath。如果可能的话,你能指点我一些关于 xpath 的好教程吗?
    • 添加了参考
    • @MesutGUNES &gt;&gt;&gt; 是什么?事实上,请你解释一下这整行代码driver.find_element_by_xpath("//bdi[text()='ASIN']/ancestor::li").text.split(": ")[1] &gt;&gt;&gt; 'B07QKN2ZT9'在做什么?
    猜你喜欢
    • 1970-01-01
    • 2021-11-05
    • 2021-05-08
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2019-07-16
    相关资源
    最近更新 更多