[英]How to get all links on a web page using python and selenium IDE
[英]Using selenium in python for capturing the links in a web
我正在嘗試使用 Python 中的 Selenium 捕獲網頁的鏈接。 我的初始代碼是:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import pandas as pd
import time
from tqdm import tqdm
from selenium.common.exceptions import NoSuchElementException
driver.get('https://www.lovecrave.com/shop/')
然后,我使用以下方法識別了 web 中的所有產品 (12):
perso_flist = driver.find_elements_by_xpath("//p[@class='excerpt']")
然后,我想使用以下方法捕獲每個產品的鏈接:
listOflinks = []
for i in perso_flist:
link_1=i.find_elements_by_xpath(".//a[@href[1]]")
listOflinks.append(link_1)
print(listOflinks
我的 output 看起來像:
print(listOflinks) # 12 EMPTY VALUES
[[], [], [], [], [], [], [], [], [], [], [], []]
我的代碼有什么問題? 我會感謝你的幫助。
我正在對這個 xpath //p[@class='excerpt']
做出一些假設,如果下面不起作用,請添加元素的 htlm 示例。
您可以通過進行此更新來獲取鏈接元素列表:
perso_flist = driver.find_elements_by_xpath("//li//a[@class='full-link']")
然后使用element.get_attribute()
遍歷列表
listOflinks = []
for i in perso_flist:
link_1=i.get_attribute("href")
listOflinks.append(link_1)
print(listOflinks)
基本上,您遍歷 a 標簽並獲取屬性 href。
hrefs=[x.get_attribute("href") for x in driver.find_elements_by_xpath("//p[@class='excerpt']/following-sibling::a[1]")]
print(hrefs)
或 xpath //li/a[@class='full-link']
輸出
['https://www.lovecrave.com/products/duet-pro/',
'https://www.lovecrave.com/products/vesper/',
'https://www.lovecrave.com/products/wink/',
'https://www.lovecrave.com/products/duet/',
'https://www.lovecrave.com/products/duet-flex/',
'https://www.lovecrave.com/products/flex/',
'https://www.lovecrave.com/products/pocket-vibe/',
'https://www.lovecrave.com/products/bullet/',
'https://www.lovecrave.com/products/cuffs/',
'https://www.lovecrave.com/shop/gift-card/',
'https://www.lovecrave.com/shop/leather-case/',
'https://www.lovecrave.com/shop/vesper-replacement-charger/']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.