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

Xon*_*hiz 21 python selenium web-scraping selenium-webdriver

我在python中练习selenium,我想使用selenium获取网页上的所有链接.

例如,我想要来自这个网站的'a href'标签中的所有链接:http://psychoticelites.com/

我写了一个脚本,它正在运行.但是,它给了我对象地址.我尝试使用'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)
Run Code Online (Sandbox Code Playgroud)

任何类型的线索/提示将不胜感激.

JRo*_*ite 45

好吧,你必须简单地遍历列表.

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

find_elements_by_*返回元素列表(注意'elements'的拼写).循环遍历列表,获取每个元素并从中获取所需的属性值.(在这种情况下href)

  • 为什么所有文档都说“不推荐”使用 xpath,但 stackoverflow 上的大多数答案都使用 xpath? (3认同)
  • XPath 不可靠。如果网站的 DOM 发生变化,那么 XPath 也会发生变化,您的脚本必然会崩溃。在处理多个脚本后,我得出的结论是将 XPath 用作最后的手段。 (2认同)
  • 像这个例子中的短xpaths它们是可靠的,如果xpath根据列/行/div等变成长字符串,我使用很多`driver.find_element_by_xpath("//*[@id='<myidentifier>']")`依赖于布局的它们不应该被使用。 (2认同)

Gab*_*elC 5

我已经检查并测试过您可以使用名为 find_elements_by_tag_name() 的函数。这个例子对我来说很好。

elems = driver.find_elements_by_tag_name('a')
    for elem in elems:
        href = elem.get_attribute('href')
        if href is not None:
            print(href)
Run Code Online (Sandbox Code Playgroud)


sri*_*s s 5

driver.get(URL)
time.sleep(7)
elems = driver.find_elements_by_xpath("//a[@href]")
for elem in elems:
    print(elem.get_attribute("href"))
driver.close()
Run Code Online (Sandbox Code Playgroud)

注意:添加延迟非常重要。首先在调试模式下运行它并确保您的 URL 页面已加载。如果页面加载缓慢,请增加延迟(睡眠时间),然后提取。

如果您仍然遇到任何问题,请参阅下面的链接(用示例解释)或评论

使用 selenium webdriver 从网页中提取链接