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)
我已经检查并测试过您可以使用名为 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)
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 从网页中提取链接