首页 > 解决方案 > 用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 开头?

谢谢

标签: pythonseleniumweb-scrapingbeautifulsoup

解决方案


使用带有以运算符开头的 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?"]')]

推荐阅读