我在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)
好吧,你只需循环浏览列表:
find_elements_by_*
返回元素列表(注意“elements”的拼写)。循环遍历列表,获取每个元素并从中获取所需的属性值(在本例中为href
)。你可以试试这样的方法:
可以使用python中的HTML dom库导入htmldom。您可以在这里找到它并使用PIP安装它:
https://pypi.python.org/pypi/htmldom/2.0
上面的代码创建了一个HtmlDom对象。HtmlDom接受一个默认参数,即页面的url。创建dom对象后,需要调用HtmlDom的“createDom”方法。这将解析html数据并构造解析树,然后可用于搜索和操作html数据。库施加的唯一限制是数据(无论是html还是xml)必须具有根元素。
可以使用HtmlDom对象的“find”方法查询元素:
上面的代码将打印网页上的所有链接/url
相关问题 更多 >
编程相关推荐