如何使用 Python 检索动态 html 内容的值
- 2025-02-08 08:52:00
- admin 原创
- 42
问题描述:
我正在使用 Python 3,并尝试从网站检索数据。但是,这些数据是动态加载的,我现在的代码不起作用:
url = eveCentralBaseURL + str(mineral)
print("URL : %s" % url);
response = request.urlopen(url)
data = str(response.read(10000))
data = data.replace("\\n", "
")
print(data)
当我尝试查找特定值时,我找到了一个模板,例如“{{formatPrice median}}”而不是“4.48”。
我怎样才能检索值而不是占位符文本?
编辑:这是我尝试从中提取信息的特定页面。我尝试获取“中位数”,它使用模板 {{formatPrice median}}
编辑2:我已经安装并设置我的程序以使用 Selenium 和 BeautifulSoup。
我现在的代码是:
from bs4 import BeautifulSoup
from selenium import webdriver
#...
driver = webdriver.Firefox()
driver.get(url)
html = driver.page_source
soup = BeautifulSoup(html)
print "Finding..."
for tag in soup.find_all('formatPrice median'):
print tag.text
这是程序执行时的屏幕截图。不幸的是,它似乎找不到任何指定了“formatPrice median”的内容。
解决方案 1:
假设您尝试从使用 javascript 模板呈现的页面中获取值(例如诸如handlebars之类的内容),那么这就是您使用任何标准解决方案(即beautifulsoup
或requests
)所获得的结果。
这是因为浏览器使用 JavaScript 来更改其收到的内容并创建新的 DOM 元素。urllib
将像浏览器一样执行请求部分,但不执行模板渲染部分。可以在此处找到有关这些问题的良好描述。本文讨论了三个主要解决方案:
直接解析 ajax JSON
使用离线 Javascript 解释器来处理请求SpiderMonkey、crowbar
使用浏览器自动化工具splinter
此答案为选项 3 提供了更多建议,例如selenium或 watir。我曾使用 selenium 进行自动化 Web 测试,它非常方便。
编辑
从您的评论来看,这似乎是一个由 Handlebars 驱动的网站。我推荐 Selenium 和 Beautiful Soup。 此答案提供了一个很好的代码示例,可能很有用:
from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://eve-central.com/home/quicklook.html?typeid=34')
html = driver.page_source
soup = BeautifulSoup(html)
# check out the docs for the kinds of things you can do with 'find_all'
# this (untested) snippet should find tags with a specific class ID
# see: http://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class
for tag in soup.find_all("a", class_="my_class"):
print tag.text
基本上,selenium 从您的浏览器获取渲染的 HTML,然后您可以使用page_source
属性中的 BeautifulSoup 对其进行解析。祝你好运 :)
解决方案 2:
我使用了硒+铬
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
url = "www.sitetotarget.com"
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')`
解决方案 3:
我知道这是一个老问题,但有时有比使用重硒更好的解决方案。
这个Python请求模块带有 JS 支持(在后台它仍然是 Chromium),您仍然可以像平常一样使用 beautifulsoup。不过,有时如果您必须单击元素或某些东西,我想 Selenium 是唯一的选择。
解决方案 4:
建立另一个答案。我遇到了类似的问题。wget 和 curl 不再能很好地获取网页内容。它尤其难以处理动态和惰性内容。使用 Chrome(或 Firefox 或 Chromium 版本的 Edge)可以处理重定向和脚本。
下面将启动 Chrome 实例,将超时时间增加到 5 秒,并将此浏览器实例导航到 URL。我从 Jupyter 运行了此操作。
import time
from tqdm.notebook import trange, tqdm
from PIL import Image, ImageFont, ImageDraw, ImageEnhance
from selenium import webdriver
driver = webdriver.Chrome('/usr/bin/chromedriver')
driver.set_page_load_timeout(5)
time.sleep(1)
driver.set_window_size(2100, 9000)
time.sleep(1)
driver.set_window_size(2100, 9000)
## You can manually adjust the browser, but don't move it after this.
## Do stuff ...
driver.quit()
抓取动态内容和锚定(因此有“a”标签)HTML 对象截图的示例,超链接的另一个名称:
url = 'http://www.example.org' ## Any website
driver.get(url)
pageSource = driver.page_source
print(driver.get_window_size())
locations = []
for element in driver.find_elements_by_tag_name("a"):
location = element.location;
size = element.size;
# Collect coordinates of object: left/right, top/bottom
x1 = location['x'];
y1 = location['y'];
x2 = location['x']+size['width'];
y2 = location['y']+size['height'];
locations.append([element,x1,y1,x2,y2, x2-x1, y2-y1])
locations.sort(key = lambda x: -x[-2] - x[-1])
locations = [ (el,x1,y1,x2,y2, width,height)
for el,x1,y1,x2,y2,width,height in locations
if not (
## First, filter links that are not visible (located offscreen or zero pixels in any dimension)
x2 <= x1 or y2 <= y1 or x2<0 or y2<0
## Further restrict if you expect the objects to be around a specific size
## or width<200 or height<100
)
]
for el,x1,y1,x2,y2,width,height in tqdm(locations[:10]):
try:
print('-'*100,f'({width},{height})')
print(el.text[:100])
element_png = el.screenshot_as_png
with open('/tmp/_pageImage.png', 'wb') as f:
f.write(element_png)
img = Image.open('/tmp/_pageImage.png')
display(img)
except Exception as err:
print(err)
mac+chrome 的安装:
pip install selenium
brew cask install chromedriver
brew cask install google-chrome
我最初使用 Mac 来回答这个问题,更新后通过 WSL2 使用 Ubuntu + Windows 11 预览版。Chrome 从 Linux 端运行,使用 Windows 上的 X 服务来呈现 UI。
关于责任,请尊重每个网站上的 robots.txt。