簡體   English   中英

點擊 python 中 Selenium 的多個鏈接

[英]Click on multiple links with Selenium in python

我正在嘗試從如下所示的結構中抓取數據:

<div class = "tables">
        <div class = "table1">
            <div class = "row">
                <div class = 'data'>Useful Data</div>
                <a href = "url1"
            </div>
            <div class = "row">
                <div class = 'data'>Useful Data</div>
                <a href = "url1">
            </div>
        </div>
        
        <div class = "table2">
            <div class = "row">
                <div class = 'data'>Useful Data</div>
                <a href = "url3"
            </div>
            <div class = "row">
                <div class = 'data'>Useful Data</div>
                <a href = "url4">
            </div>
        </div>
     </div>

我想要的數據在 div“數據”中,並且在通過單擊 url 可訪問的其他一些頁面上。 我使用 BeautifulSoup 遍歷“表”,並嘗試單擊 Selenium 的鏈接,如下所示:

tables = soup.find_all('div', class_ = 'tables')
 for line in tables:
     row = line.find_all('div', class_ = "row")
     for element in row:
         link = driver.find_element_by_xpath('//a[contains(@href,"href")]')
         #some code

在我的腳本中,這一行

link = driver.find_element_by_xpath('//a[contains(@href,"href")]')

總是返回第一個 url,當我希望它“關注”BeautifulSoup 並返回以下 hrefs 時。 那么有沒有辦法根據源代碼中的 url 修改href? 我應該補充一點,我所有的網址都非常相似,除了最后一部分。 (例如:url1 = questions/ask/ 1000 , url2 = questions/ask/ 1001

我還嘗試在頁面中找到所有 href 以使用它們進行迭代

links = self.driver.find_element_by_xpath('//a[@href]')

但這也不起作用。 由於該頁面包含許多對我無用的鏈接,我不確定這是否是 go 的最佳方式。

似乎有點復雜 - 為什么不直接用BeautifulSoup提取href

for a in soup.select('.tables a[href]'):
    link = a['href']

您還可以修改它,與 baseUrl 連接並存儲在列表中以進行迭代:

urls = [baseUrl+a['href'] for a in soup.select('.tables a[href]')]

例子

baseUrl = 'http://www.example.com'

html='''
<div class = "tables">
        <div class = "table1">
            <div class = "row">
                <div class = 'data'>Useful Data</div>
                <a href = "/url1"
            </div>
            <div class = "row">
                <div class = 'data'>Useful Data</div>
                <a href = "/url1">
            </div>
        </div>

        <div class = "table2">
            <div class = "row">
                <div class = 'data'>Useful Data</div>
                <a href = "/url3"
            </div>
            <div class = "row">
                <div class = 'data'>Useful Data</div>
                <a href = "/url4">
            </div>
        </div>
     </div>'''
soup = BeautifulSoup(html,'lxml')

urls = [baseUrl+a['href'] for a in soup.select('.tables a[href]')]

for url in urls:
    print(url)#or request the website,....

Output

http://www.example.com/url1
http://www.example.com/url1
http://www.example.com/url3
http://www.example.com/url4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM