gpt4 book ai didi

python - 使用 beautifulsoup4 进行抓取时数据丢失

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

实际上,我是使用 Python Beautifulsoup4 进行解析的新手。我在抓取 this website .我需要在首页上显示当前每百万美元的价格

我已经为此花费了 3 个小时。在互联网上寻找解决方案时。我知道有一个 PyQT4 库可以像 Web 浏览器一样模仿并加载内容,然后一旦完成加载,您就可以提取您需要的数据。但是我崩溃了。

使用这种方法以原始文本格式收集数据。我也尝试了其他方法。

def parseMe(url):
soup = getContent(url)
source_code = requests.get(url)
plaint_text = source_code.text
soup = BeautifulSoup(plaint_text, 'html.parser')
osrs_text = soup.find('div', class_='col-md-12 text-center')
print(osrs_text.encode('utf-8'))

Please have a look on this image .我认为问题出在::before 和::after 标签上。它们会在页面加载后出现。
我们将不胜感激任何帮助。

最佳答案

你应该使用 selenium 而不是 `requests:

from selenium import webdriver
from bs4 import BeautifulSoup

def parse(url):
driver = webdriver.Chrome('D:\Programming\utilities\chromedriver.exe')
driver.get('https://boglagold.com/buy-runescape-gold/')
soup = BeautifulSoup(driver.page_source)
return soup.find('h4', {'id': 'curr-price-per-mil-text'}).text

parse()

输出:

'Current Price Per Mil: 0.80USD'

原因是那个元素的值是通过JavaScript获取的,requests无法处理。这个特定的代码片段使用了 Chrome 驱动程序;如果您愿意,可以使用 Firefox/其他一些等效浏览器(您需要安装 selenium 库并自行寻找 Chrome 驱动程序)。

关于python - 使用 beautifulsoup4 进行抓取时数据丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55329489/

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