[英]How to retrieve the values of dynamic html content using Python
我正在使用 Python 3,并且正在尝试从网站检索数据。 但是,这些数据是动态加载的,我现在拥有的代码不起作用:
url = eveCentralBaseURL + str(mineral)
print("URL : %s" % url);
response = request.urlopen(url)
data = str(response.read(10000))
data = data.replace("\\n", "\n")
print(data)
在我试图找到特定值的地方,我找到了一个模板,例如“{{formatPrice medium}}”而不是“4.48”。
我该如何制作它以便我可以检索值而不是占位符文本?
编辑:这是我试图从中提取信息的特定页面。 我正在尝试获取“中值”值,该值使用模板 {{formatPrice 中值}}
编辑 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 中位数”的东西。
假设您正在尝试从使用 javascript 模板(例如像handlebars 之类的东西)呈现的页面获取值,那么这就是您使用任何标准解决方案(即beautifulsoup
或requests
)都会得到的值。
这是因为浏览器使用 javascript 来改变它接收到的内容并创建新的 DOM 元素。 urllib
会像浏览器一样完成请求部分,而不是模板渲染部分。 可以在此处找到对这些问题的详细描述。 本文讨论了三种主要解决方案:
此答案为选项 3 提供了更多建议,例如selenium或 watir。 我使用 selenium 进行自动化 Web 测试,它非常方便。
编辑
从您的评论来看,它看起来像是一个车把驱动的网站。 我推荐硒和美丽的汤。 这个答案给出了一个很好的代码示例,它可能很有用:
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 解析它。 祝你好运 :)
我用硒+铬
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')`
建立另一个答案。 我有一个类似的问题。 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
更新后,我通过 WSL2 使用 Mac 作为原始答案和 Ubuntu + Windows 11 预览。 Chrome 从 Linux 端运行,在 Windows 上使用 X 服务来呈现 UI。
关于责任,请尊重每个网站上的robots.txt。
我知道这是一个老问题,但有时有比使用重硒更好的解决方案。
这个python的请求模块带有JS支持(在后台它仍然是chrome),你仍然可以像往常一样使用beautifulsoup。 但是,有时如果您必须单击元素或某物,我想硒是唯一的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.