blu*_*fer 7 python selenium beautifulsoup web
我使用Python和BeautifulSoup4,我需要检索页面上的可见链接.鉴于此代码:
soup = BeautifulSoup(html)
links = soup('a')
Run Code Online (Sandbox Code Playgroud)
我想创建一个方法is_visible,检查页面上是否显示链接.
由于我也在与Selenium合作,因此我知道存在以下解决方案:
from selenium.webdriver import Firefox
firefox = Firefox()
firefox.get('https://google.com')
links = firefox.find_elements_by_tag_name('a')
for link in links:
if link.is_displayed():
print('{} => Visible'.format(link.text))
else:
print('{} => Hidden'.format(link.text))
firefox.quit()
Run Code Online (Sandbox Code Playgroud)
不幸的是,is_displayed方法和获取text属性执行http请求以检索此类信息.因此,当页面上有许多链接或者您必须多次执行此操作时,事情会变得非常慢.
另一方面,一旦获得页面源,BeautifulSoup可以在零时间内执行这些解析操作.但我无法弄清楚如何做到这一点.
小智 1
AFAIK,BeautifulSoup 只会帮助您解析 HTML 文档的实际标记。如果这就是您所需要的,那么您可以按照这样的方式进行(是的,我已经知道它并不完美):
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc)
def is_visible_1(link):
#do whatever in this function you can to determine your markup is correct
try:
style = link.get('style')
if 'display' in style and 'none' in style:#or use a regular expression
return False
except Exception:
return False
return True
def is_visible_2(**kwargs):
try:
soup = kwargs.get('soup', None)
del kwargs['soup']
#Exception thrown if element can't be found using kwargs
link = soup.find_all(**kwargs)[0]
style = link.get('style')
if 'display' in style and 'none' in style:#or use a regular expression
return False
except Exception:
return False
return True
#checks links that already exist, not *if* they exist
for link in soup.find_all('a'):
print(str(is_visible_1(link)))
#checks if an element exists
print(str(is_visible_2(soup=soup,id='someID')))
Run Code Online (Sandbox Code Playgroud)
BeautifulSoup不会考虑其他方面来告诉您元素是否可见,例如:CSS、脚本和动态 DOM 更改。另一方面,Selenium 确实会告诉您某个元素实际上是否正在渲染,并且通常是通过给定浏览器中的可访问性 API 来实现的。您必须决定是否值得为了速度而牺牲准确性。祝你好运!:-)
| 归档时间: |
|
| 查看次数: |
6032 次 |
| 最近记录: |