python - 用selenium python从不同的html中获取href标签下的链接
问题描述
我在网页中进行不同的搜索,我想从每个搜索中获取 href 标记下的链接。我感兴趣的 html 部分如下所示:
<tbody>
<tr>
<td style='width:. 507px; height: 20px;' colspan='2'>
<a href='https://www.webpage.com/CompanyCard?982387dhsdfi83123+Ltd.' target='_blank'> 123.Ltd.
</a>
</td>
</tr>
问题是,由于每次搜索都会更改 html 页面,因此我无法找到该页面来使用 beautifulsoup。
到目前为止我尝试了这个但没有工作:
from selenium.webdriver import Firefox
from selenium import webdriver
import pandas as pd
from bs4 import BeautifulSoup
df=pd.read_excel('/Users/ap/list.xlsx')
opts = Options()
browser = Firefox(options=opts)
browser.get('https://www.webpage.com/')
for rows in df['firm']:
search_form1=browser.find_element_by_id('dnn_Search_tbSearch')
search_form1.send_keys(rows)
time.sleep(2)
search_form2=browser.find_element_by_id('dnn_Search_lbGo').click()
html = BeautifulSoup.find_all('td', attrs={'style': 'width: 507px; height: 20px'})
for td in html:
a= td.find('a')['href']
links.append(a)
i=i+1
如何仅提取与每个搜索的 href 相关的完整链接:' https://www.webpage.com/CompanyCard?982387dhsdfi83123+Ltd .'?**所有链接始终以:https ://www.webpage.com/CompanyCard 开头?
谢谢
解决方案
使用带有以运算符开头的 css属性 = 值选择器,指定 href 属性必须以https://www.webpage.com/CompanyCard?
例如
links = [i['href'] for i in soup.select('[href^="https://www.webpage.com/CompanyCard?"]')
你可以通过相同的模式
[href^="https://www.webpage.com/CompanyCard?"]
硒find_elements_by_css_selector
links = [i.get_attribute('href') for i in driver.find_elements_by_css_selector('[href^="https://www.webpage.com/CompanyCard?"]')]
推荐阅读
- function - 在 Dataweave 1.0 中创建全局函数
- flutter - Flutter 在搜索框中使用 REST API 从 JSON 中检索数据
- sql - 将一列排序/拆分为一行中的不同视图列
- php - laravel 没有从第一次设置会话数据
- unity3d - 修复使用 ARCore 在按钮上创建的地面上的家具
- node.js - 使用 pm2 启动时 Mongoose 中的只读属性分配错误
- jsf - 如何将 CASBIN 与 JSF 集成
- azure - 如何在 Azure 数据工厂中将 txt 转换为 csv 文件
- javascript - 我应该如何让我的 jquery 验证器工作?(我认为它不会等待远程规则)
- python - 如何使用 sqlalchemy 在 Web 浏览器上显示 postgresql 数据库表数据?