建立另一个答案。我有一个类似的问题。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 在 Windows 上使用 X 服务从 Linux 端运行以呈现 UI。
关于责任,请尊重每个网站上的 robots.txt。