web-scraping - 使用 BeautifulSoup 获取 span 中的 span 的文本
问题描述
我正在尝试使用此站点上的 Beautiful Soup 从站点返回 城市、国家和地区: https ://www.geodatatool.com/en/?ip=82.47.160.231 (别担心这不是我的 IP ; 虚拟IP)
这就是我正在尝试的:
url = "https://www.geodatatool.com/en/?ip="+ip
# Getting site's data in plain text..
sourceCode = requests.get(url)
plainText = sourceCode.text
soup = BeautifulSoup(plainText)
tags = soup('span')
# Parsing data.
data_item = soup.body.findAll('div','data-item')
#bold_item = data_item.findAll('span')
for tag in tags:
print(tag.contents)
我只是得到一个包含所有跨度内容的数组。试图将其范围缩小到具体我的需求,但这不会很快发生。
有人可以帮我解决这个问题吗?
解决方案
这应该有效。基本上我们找到所有具有类:'data-item'的div,然后在这里我们正在寻找2个跨度,其中第一个跨度是城市:,国家:等,第二个跨度包含数据。
data_items = soup.findAll('div', {'class': 'data-item'})
# Country
country = data_items[2].findAll('span')[1].text.strip()
# City
city = data_items[5].findAll('span')[1].text.strip()
# Region
country = data_items[4].findAll('span')[1].text.strip()
一般来说,这是可行的,但如果网站显示不同的数据或每次搜索对数据排序不同,我们可能希望使代码更健壮一些。我们可以通过使用正则表达式来查找国家、城市和地区字段来做到这一点。解决方案如下:
# Country
country = soup.find(text=re.compile('country', re.IGNORECASE)).parent.parent.findAll('span')[1].text.strip()
# City
city = soup.find(text=re.compile('city', re.IGNORECASE)).parent.parent.findAll('span')[1].text.strip()
# Region
region = soup.find(text=re.compile('region', re.IGNORECASE)).parent.parent.findAll('span')[1].text.strip()
我们尝试在 HTML 代码中找到模式“国家”、“城市”或“地区”。然后抓取它们的父级 2 次以获得与之前代码块中的 data_items 相同的结果,并执行相同的操作以获得答案。
推荐阅读
- sas - SAS Enterprise Guide – 拆分/堆叠列
- flutter - 下拉选择不会使用 Flutter 更改为当前值
- python - 线程在 Tkinter 的 recv 函数上的 UDP 套接字服务器上不起作用
- verilog - 2^n 到 n 优先级编码器,带连续分配
- r - 将前导零添加到列表并将修改后的值分配回数据框中的变量
- python - 在 Python 中使用 scipy.odeint 方法进行多次返回
- python - 如何从具有许多不同前景的图像中提取任意背景矩形块
- ffmpeg - 是否可以在文本文件中而不是在命令行中向 FFmpeg 提供输入文件列表?
- javascript - 如何在Angular 9的html页面中打印控制台上显示的数据
- python - 如何将边的二分列表转换为 NetworkX 中的图,每组节点都具有重叠标签?