无法从包含过滤器的网站中提取文本

问题描述 投票:0回答:1

[我正在尝试使用Python,以及Requests和BeautifulSoup,将所有位置从以下网站(www.mars.com/locations)中移出。

该网站具有用于选择大洲,国家和地区的过滤器,因此它将仅显示公司在所选区域中的位置。它们的总部也位于页面底部,无论使用什么过滤器,该信息始终存在。

我使用下面的代码为总部提取数据没有问题:

import requests
from bs4 import BeautifulSoup

url = 'https://www.mars.com/locations'

page = requests.get(url)
soup = BeautifulSoup(page.text,'html.parser')

HQ = soup.find('div', class_='global-headquarter pr-5 pl-3').text.strip()

print(HQ)

代码的输出是:

Mars,Incorporated(全球总部)榆树街6885号麦克莱恩维吉尼亚州22101+1(703)821-4900

我想对所有其他位置执行相同的操作,但是我正努力使用相同的方法(当然要调整路径)提取数据。我已经尝试了一切,但没有主意。非常感谢有人帮我或至少指向我正确的方向。

非常感谢!

python beautifulsoup python-requests screen-scraping filtered
1个回答
1
投票

所有位置数据都可以以文本格式检索。将其分解为字符串是一种方法。我不是该领域的专家,所以我再也不能帮助您。

content_json = soup.find('div', class_='location-container')
data = content_json['data-location']

0
投票

我不是BeautifulSoup的专家,所以我将使用parsel来获取数据。所有位置都嵌入到具有location-container属性的data-location css类中。

import requests
from parsel import Selector
response = requests.get(url).text
selector = Selector(text=response)
data = selector.css(".location-container").xpath("./@data-location").getall()
© www.soinside.com 2019 - 2024. All rights reserved.