Python靓汤:针对一个特定的elemen

2024-04-24 23:39:37 发布

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

我正试图抓取网站的某个特定部分(https://flightmath.com/from-CDG-to-BLR),但我无法针对我需要的元素。你知道吗

下面是html的一部分

<h2 style="background-color:#7DC2F8;padding:10px"><i class="fa fa-plane"></i> &nbsp;flight distance = <strong>4,866</strong> miles</h2>

这是我的密码

dist = soup.find('h2', attrs={'class': 'fa fa-plane'}) 

我只想瞄准“4866”部分。你知道吗

如果有人能在这方面指导我,我将不胜感激。 提前谢谢。你知道吗


Tags: tofromhttpscom元素网站h2cdg
3条回答

attrs={'class': '...'}需要精确的class属性值(不是组合)。
相反,使用soup.select_one方法按扩展的css规则选择:

from bs4 import BeautifulSoup
import requests

url = 'https://flightmath.com/from-CDG-to-BLR'
html_data = requests.get(url).content
soup = BeautifulSoup(html_data, 'html.parser')

dist = soup.select_one('h2 i.fa-plane + strong')
print(dist.text)   # 4,866

感兴趣的情况下:该值被硬编码到html中(用于飞行速度计算),因此您还可以使用下面的正则表达式输出更精确的值。您可以使用round()获取页面上显示的值。你知道吗

import requests, re

urls = ['https://flightmath.com/from-CDG-to-BOM', 'https://flightmath.com/from-CDG-to-BLR', 'https://flightmath.com/from-CDG-to-IXC']
p = re.compile(r'flightspeed\.min\.value\/60 \+ ([0-9.]+)')
with requests.Session() as s:
    for url in urls:
        print(p.findall(s.get(url).text)[0])

查找具有类名的标记,然后使用find_next()查找强标记。你知道吗

from bs4 import BeautifulSoup
import requests

url = 'https://flightmath.com/from-CDG-to-BLR'
html_data = requests.get(url).text
soup = BeautifulSoup(html_data, 'html.parser')
dist = soup.find('i',class_='fa-plane').find_next('strong')
print(dist.text)

相关问题 更多 >