试图用beautifulsoup在网页上创建一个页面,获取大量的元素数据(我猜),我想删除这些数据

2024-03-28 19:07:54 发布

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

我几乎什么都能用,但:

当用class得到一个特定的div时,我得到一个长的响应,这对我来说是无用的。在检查时,我相信这是因为div没有在我需要的信息之后结束。你知道吗

我正试图找出正确的方法,只获取我想要的数据。我知道还有另一种方法可以排除某些数据?你知道吗

代码:

soup = BeautifulSoup(source, "html.parser")
contact_us = soup.find_all("div",{"class" : "contact_us"})

输出是一个只有一个项目的列表,否则我将使用循环方法。你知道吗

[链接][1]-由于可能的敏感信息,链接已删除。你知道吗

编辑:

我想得到:

公司名称 联系人 地址: 移动电话: 电话:


Tags: 数据方法代码div信息parsersource链接
1条回答
网友
1楼 · 发布于 2024-03-28 19:07:54

标记不太容易使用,但我们可以使用strong元素作为我们可以依赖的东西—逐个定位strong元素,将它们用作标签,然后我们可以前进到next siblings,直到遇到另一个strong元素或到达终点:

from itertools import takewhile

import requests
from bs4 import BeautifulSoup, Tag

url = "http://www.htavr.com/enquiry.html"
response = requests.get(url)

soup = BeautifulSoup(response.content, "html5lib")
contact_us = soup.select_one(".contact_us")

# remove all br elements to ease parsing
for br in contact_us.find_all("br"):
    br.unwrap()

labels = contact_us.find_all("strong")

# first strong element is a business name
business_name = labels[0].get_text()

not_tag = lambda elm: not isinstance(elm, Tag)

# going over all the strong "labels"
for label in labels[1:]:
    # extract all next text nodes before the next "strong" element or the end
    value = " ".join([text.strip() for text in takewhile(not_tag, label.next_siblings)])

    print(label.get_text(strip=True), value)

印刷品:

Contact Person : <first_and_last_name> (Director)
Address : <address_here>
Mobile : <mobiles_here>
Phone : <telephones_here>
Call Us : <telephone_here>

(从答案中删除敏感信息)

相关问题 更多 >