如何使用Selenium从网页获取所有元素?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用Selenium从网页获取所有元素?相关的知识,希望对你有一定的参考价值。
我的Python代码只找到html的第一篇文章,所以它打印的是同一个链接。如何从HTML获取所有文章标签?谢谢。
Python代码:
links = driver.find_elements_by_tag_name("article")
for i in links:
if driver.find_element_by_xpath("//div[@class='inner-article']/a//div[@class='sold_out_tag']").get_attribute("innerHTML") == "sold out":
print("sold out")
link = ((driver.find_element_by_xpath("//div[@class='inner-article']/a").get_attribute("href")))
print(link)
else:
print("available")
time.sleep(5)
driver.quit()
HTML:
<article>
<div class="inner-article"><a style="height:81px;"
href="/shop/jackets/jly8dgwqu/w10m2pybx"><img width="81" height="81"
src="//d17ol771963kd3.cloudfront.net/139432/vi/AHP1l8fMIcA.jpg"
alt="Ahp1l8fmica"><div class="sold_out_tag">sold out</div></a></div>
</article>
<article>
<div class="inner-article"><a style="height:81px;"
href="/shop/jackets/jly8dgwqu/w10m2pybx"><img width="81" height="81"
src="//d17ol771963kd3.cloudfront.net/139432/vi/AHP1l8fMIcA.jpg"
alt="Ahp1l8fmica"><div class="sold_out_tag">sold out</div></a></div>
</article>
答案
要做到这一点,你需要一个名为Action Chains的Selenium特殊机动。您可以在顶部导入它,如下所示:
from selenium.webdriver.common.action_chains import ActionChains
然后继续如下:
articles = driver.find_elements_by_tag_name('article')
for article in articles:
ActionChains(driver).move_to_element(article).perform()
if article.find_element_by_tag_name('a').text == "sold out":
print("sold out")
link = article.find_element_by_xpath('div/a').get_attribute('href')
print(link)
else:
print("available")
对于每个文章web元素,您可以从driver
调用相同的方法来查看该元素。 XPath的双斜杠(//
)规定它搜索整个DOM而不考虑任何特定元素(这就是为什么它每次都找到相同的元素),所以你需要搜索它的直接子元素(即./
)。
编辑:默认情况下,带有售罄文本的元素的CSS属性为display: none;
。触发售罄文本的唯一方法是将鼠标悬停在每个元素上。幸运的是,Selenium也有这种能力。我也改变了我的原始代码,没有售罄的商品没有带有“售罄标签”类的div,因此会导致错误。
另一答案
根据您分享的HTML
,如果您想用文本href
打印节点的sold out
s,您可以使用以下代码块:
links = driver.find_elements_by_tag_name("article")
for i in links:
if "sold out" in i.find_elements_by_xpath("//div[@class='inner-article']/a//div[@class='sold_out_tag']").get_attribute("innerHTML") :
print("sold out")
print(i.find_element_by_xpath("//div[@class='inner-article']/a").get_attribute("href"))
以上是关于如何使用Selenium从网页获取所有元素?的主要内容,如果未能解决你的问题,请参考以下文章