首页 > 解决方案 > 使用 Beautifulsoup 和 Selenium 从 JavaScript 驱动的页面解析 URL

问题描述

我想解析发生任何电子邮件的 Git 存储库中的所有 URL。我使用https://grep.app

编码:

from bs4 import BeautifulSoup
from selenium import webdriver
url = 'https://grep.app/search?current=100&q=%40gmail.com'
chrome = "/home/dev/chromedriver"
browser = webdriver.Chrome(executable_path=chrome)
browser.get(url)
html = browser.page_source
soup = BeautifulSoup(html, 'lxml')
tags = soup.select('a')
print(tags)

当代码启动时,Chrome 启动并加载结果页面,在 Chrome 的开发人员工具中,在源代码中我可以看到很多 URL 的 A 和 HREF。 页面来源

喜欢: lib/plugins/revert/lang/eu/lang.php

但我的代码只从页脚返回“标签”:

"[<a href="/"><span class="slashes">//</span>grep.app</a>, <a href="mailto:hello@grep.app">Contact</a>]"

据我了解JS解析有问题。请指教我做错了什么?

标签: javascriptpythonseleniumbeautifulsoupwebdriver

解决方案


代码:

from bs4 import BeautifulSoup
from selenium import webdriver

url = 'https://grep.app/search?current=100&q=%40gmail.com'
chrome = "/home/dev/chromedriver"
browser = webdriver.Chrome(executable_path=chrome)
browser.get(url)

html = browser.page_source
soup = BeautifulSoup(html, 'lxml')

links = []
tags = soup.find_all('a', href=True)
for tag in tags:
    links.append(tag['href'])
    
print(links)

输出:

['/', 'mailto:hello@grep.app']

推荐阅读