Python 使用selenium和类进行web解析
我试图解析一个博客中的几个项目,但我无法找到我需要的最后两个项目 html是:Python 使用selenium和类进行web解析,python,selenium,Python,Selenium,我试图解析一个博客中的几个项目,但我无法找到我需要的最后两个项目 html是: <div class="post"> <div class="postHeader"> <h2 class="postTitle"><span></span><a href="http://website.com" title="cuba and the cameraman">
<div class="post">
<div class="postHeader">
<h2 class="postTitle"><span></span><a href="http://website.com" title="cuba and the cameraman">cuba and the cameraman</a></h2>
<span class="postMonth" title="2017">Nov</span>
<span class="postDay" title="2017">24</span>
<div class="postSubTitle"><span class="postCategories"><a href="http://website.com" rel="category tag">TV Shows</a></span></div>
</div>
<div class="postContent"><p><a target="_blank" href="https://image.com/test.jpg"><img class="aligncenter" src="https://image.com/test.jpg"/></a> <br />
n/A<br />
<br />
<strong>Links:</strong> <a target='_blank' href='http://www.imdb.com/title/tt7320560/'>IMDB</a><br />
</p>
但是我不能使用与上面相同的方法,类名来获取图像和imdb链接。
你能支持我吗?谢谢。您需要更精确的搜索,有一系列内置的
find\u element\u by\u XX
函数,请尝试xpath:
for post in driver.find_elements_by_xpath('//div[@class="post"]'):
title = post.find_element_by_xpath('.//h2[@class="postTitle"]//a').text
img_src = post.find_element_by_xpath('.//div[@class="postContent"]//img').get_attribute('src')
link = post.find_element_by_xpath('.//div[@class="postContent"]//a[last()]').get_attribute('href')
请记住,您随时可以通过
driver.page\u source
获取html源代码,并使用您喜欢的任何工具对其进行解析。谢谢。2个问题;你的意思是属性而不是产权?另一个问题,如果我想要第二个链接,而不是href最后一个链接的[last()],该怎么办?刚刚注意到链接:有3个链接,我只需要第二个。再次感谢。是的,get\u属性
更准确,对于选择第二个链接,您可以使用数字,而不是像//div[@class=“postContent”]//a[2]
for post in driver.find_elements_by_xpath('//div[@class="post"]'):
title = post.find_element_by_xpath('.//h2[@class="postTitle"]//a').text
img_src = post.find_element_by_xpath('.//div[@class="postContent"]//img').get_attribute('src')
link = post.find_element_by_xpath('.//div[@class="postContent"]//a[last()]').get_attribute('href')