python - 在 python 中使用 selenium 来捕获网络中的链接
问题描述
我正在尝试在 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/')
然后,我使用以下方法识别了网络中的所有产品 (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
我的输出看起来像:
print(listOflinks) # 12 EMPTY VALUES
[[], [], [], [], [], [], [], [], [], [], [], []]
我的代码有什么问题?我会感谢你的帮助。
解决方案
基本上,您遍历 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/']
推荐阅读
- python - 在 mongodb 中使用 python3 中的变量自动创建数据库名称中的探针
- ios - ios web places api 获取评分和评论
- google-cloud-platform - SQL Select 语句的 Spanner 日志记录
- google-api - 如何使用 google-api-java-client 在没有浏览器的情况下实现 0Auth2
- javascript - Vue.js 使用 post 方法重定向
- javascript - javascript 时间表上的表单输入有问题
- mysql - MySQL 选择计数和行计数
- deezer - oAuth 身份验证 - 即使一切正常,令牌也始终无效
- cassandra - 有效地以多租户格式对数据进行分区。
- vba - ClipboardFormat 值 44 和 50 的含义