在python中使用selenium获取所有的ref链接

2024-09-27 09:36:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中练习Selenium,我想使用Selenium获取web页面上的所有链接。

例如,我想要http://psychoticelites.com/上所有<a>标记的href=属性中的所有链接

我已经写了一个脚本,它正在工作。但是,它给了我目标地址。我试过使用id标记来获取值,但是,它不起作用。

我当前的脚本:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys


driver = webdriver.Firefox()
driver.get("http://psychoticelites.com/")

assert "Psychotic" in driver.title

continue_link = driver.find_element_by_tag_name('a')
elem = driver.find_elements_by_xpath("//*[@href]")
#x = str(continue_link)
#print(continue_link)
print(elem)

Tags: from标记import脚本comhttp链接driver
3条回答

好吧,你只需循环浏览列表:

elems = driver.find_elements_by_xpath("//a[@href]")
for elem in elems:
    print(elem.get_attribute("href"))

find_elements_by_*返回元素列表(注意“elements”的拼写)。循环遍历列表,获取每个元素并从中获取所需的属性值(在本例中为href)。

你可以试试这样的方法:

    links = driver.find_elements_by_partial_link_text('')

可以使用python中的HTML dom库导入htmldom。您可以在这里找到它并使用PIP安装它:

https://pypi.python.org/pypi/htmldom/2.0

from htmldom import htmldom
dom = htmldom.HtmlDom("https://www.github.com/")  
dom = dom.createDom()

上面的代码创建了一个HtmlDom对象。HtmlDom接受一个默认参数,即页面的url。创建dom对象后,需要调用HtmlDom的“createDom”方法。这将解析html数据并构造解析树,然后可用于搜索和操作html数据。库施加的唯一限制是数据(无论是html还是xml)必须具有根元素。

可以使用HtmlDom对象的“find”方法查询元素:

p_links = dom.find("a")  
for link in p_links:
  print ("URL: " +link.attr("href"))

上面的代码将打印网页上的所有链接/url

相关问题 更多 >

    热门问题