【问题标题】:How to extract or Scrape data from HTML page but from the element itself如何从 HTML 页面但从元素本身提取或抓取数据
【发布时间】:2019-11-15 18:05:29
【问题描述】:

目前我使用 lxml 来解析 html 文档以从 HTML 元素中获取数据 但是有一个新的挑战,有一个数据作为评分存储在 HTML 元素中

https://i.stack.imgur.com/bwGle.png

<p data-rating="3">
                                <span class="glyphicon glyphicon-star xh-highlight"></span>
                                <span class="glyphicon glyphicon-star xh-highlight"></span>
                                <span class="glyphicon glyphicon-star xh-highlight"></span>
                            </p>

在标签之间提取文本很容易,但在标签内没有想法。 你有什么建议?

挑战我要提取“3” 网址:https://webscraper.io/test-sites/e-commerce/allinone/computers/laptops

兄弟, 加布里埃尔。

【问题讨论】:

  • 给我们您的脚本,我们会检查它。谢谢。

标签: python lxml


【解决方案1】:

如果我正确理解了您的问题和 cmets,则以下内容应提取该页面中的所有评分:

import lxml.html
import requests

BASE_URL = "https://webscraper.io/test-sites/e-commerce/allinone/computers/laptops"

html = requests.get(BASE_URL)
root = lxml.html.fromstring(html.text)
targets = root.xpath('//p[./span[@class]]/@data-rating')

例如:

targets[0]

输出

3

【讨论】:

    【解决方案2】:

    试试下面的脚本:

    from bs4 import BeautifulSoup
    import requests
    
    BASE_URL = "https://webscraper.io/test-sites/e-commerce/allinone/computers/laptops"
    
    html = requests.get(BASE_URL).text
    soup = BeautifulSoup(html, "html.parser")
    for tag in soup.find_all("div", {"class":"ratings"}):
        # get all child from the tags
        for h in tag.children:
            # convert to string data type
            s = h.encode('utf-8').decode("utf-8") 
    
            # find the tag with data-rating and get text after the keyword
            m = re.search('(?<=data-rating=)(.*)', s)
    
            # check if not None
            if m:
                #print the text after data-rating and remove last char
                print(m.group()[:-1])
    

    【讨论】:

    • 你能给我一个lxml的例子吗???而不是美丽的汤。因为我已经用 Lxml 和 xpath 解析元素实现了代码的另一部分。
    • 给我看你的脚本的一部分,以便我可以帮助你。
    • 我改成soup = BeautifulSoup(html, "lxml") 也可以了
    • 嗨,当然,我会分享它,但你会如何在美丽的汤中使用 xpath??
    猜你喜欢
    • 2011-03-23
    • 2015-07-15
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多