如何从HTML页面但从元素本身提取或刮取数据

2024-05-13 21:00:35 发布

您现在位置:Python中文网/ 问答频道 /正文

目前,我使用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

比尔, 加布里埃尔


Tags: 数据文档https元素stackhtml标签lxml
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])

如果我正确理解您的问题和评论,以下内容应摘录该页面中的所有评分:

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

相关问题 更多 >