在Python中使用Selenium获取来自某个div的链接 [英] Get links from a certain div using Selenium in Python
问题描述
我有以下HTML页面.我想获取特定div中的所有链接.这是我的HTML代码:
I have the following HTML page. I want to get all the links inside a specific div. Here is my HTML code:
<div class="rec_view">
<a href='www.xyz.com/firstlink.html'>
<img src='imga.png'>
</a>
<a href='www.xyz.com/seclink.html'>
<img src='imgb.png'>
</a>
<a href='www.xyz.com/thrdlink.html'>
<img src='imgc.png'>
</a>
</div>
我想获取rec_view
div上存在的所有链接.所以我想要的那些链接是
I want to get all the links that are present on the rec_view
div. So those links that I want are,
www.xyz.com/firstlink.html
www.xyz.com/seclink.html
www.xyz.com/thrdlink.html
这是我尝试过的Python代码
Here is the Python code which I tried with
from selenium import webdriver;
webpage = r"https://www.testurl.com/page/123/"
driver = webdriver.Chrome("C:\chromedriver_win32\chromedriver.exe")
driver.get(webpage)
element = driver.find_element_by_css_selector("div[class='rec_view']>a")
link = element.get_attribute("href")
print(link)
如何在Python上使用Selenium来获得那些链接?
How can I get those links using selenium on Python?
推荐答案
根据您共享的HTML来获取rec_view
div上存在的所有链接的列表,您可以使用以下代码块:
As per the HTML you have shared to get the list of all the links that are present on the rec_view
div you can use the following code block :
from selenium import webdriver
driver = webdriver.Chrome(executable_path=r'C:\chromedriver_win32\chromedriver.exe')
driver.get('https://www.testurl.com/page/123/')
elements = driver.find_elements_by_css_selector("div.rec_view a")
for element in elements:
print(element.get_attribute("href"))
注意:由于您需要从 div 标记中收集所有 href 属性,因此需要使用find_elements_*
.另外,>
指直接的<a>
子节点,在这里您需要遍历所有<a>
子节点,因此所需的css_selector
将为 div.rec_view a
Note : As you need to collect all the href attributes from the div tag so instead of find_element_*
you need to use find_elements_*
. Additionally, >
refers to immediate <a>
child node where as you need to traverse all the <a>
child nodes so the desired css_selector
will be div.rec_view a
这篇关于在Python中使用Selenium获取来自某个div的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!