gpt4 book ai didi

python - 按类查找跨度并提取其内容

转载 作者:太空宇宙 更新时间:2023-11-03 15:25:22 25 4
gpt4 key购买 nike

我想提取快照中给出的特定范围的文本。我无法通过其类属性找到跨度。我还附上了要提取的数据的 html 源(快照)。有什么建议吗?

import bs4 as bs
import urllib
sourceUrl='https://www.pakwheels.com/forums/t/planing-a-trip-from-karachi-to-lahore-by-road-in-feb-2017/414115/2'
source=urllib.request.urlopen(sourceUrl).read()
soup=bs.BeautifulSoup(source, 'html.parser')

count=soup.find('span',{'class':'number'})
print(len(count))

看图片:

See the image

最佳答案

如果您在浏览器中禁用 JavaScript,您可以轻松地看到您想要的 span 元素正在消失。为了获得该元素,可能的解决方案之一可以是使用 Selenium浏览器。

from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://www.pakwheels.com/forums/t/planing-a-trip-from-karachi-to-lahore-by-road-in-feb-2017/414115/2')
span = driver.find_element_by_xpath('//li[3]/span')
print(span.text)
driver.close()

输出: enter image description here

另一个解决方案 - 在网页源深处查找所需的值(在 Chrome 浏览器中按 Ctrl+U)并使用正则表达式提取跨度值。

import re
import requests
r = requests.get(
'https://www.pakwheels.com/forums/t/planing-a-trip-from-karachi-to-lahore-by-road-in-feb-2017/414115/2')
span = re.search('\"posts_count\":(\d+)', r.text)
print(span.group(1))

输出: enter image description here

关于python - 按类查找跨度并提取其内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43201492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com