我正在尝试从网站收集文本和图像,以帮助收集与失踪人员相关的推文。这是问题所在:
有些推文没有图片,因此对应的<div class='c' ....>
只有一条<div>...</div>
。有些tweet包含图片,因此相应的tweet包含<div class='c' ....>
两个<div>...</div>
,如以下代码所示:
<div class='c' id="M_D*****">
<div>...</div>
和
<div class='c' id="M_D*****">
<div>...</div>
<div>...</div>
我打算检查一条推文是否有图像,即找出对应的图像是否<div class='c' ....>
有两个<div>...</div>
。
PS:以下代码用于收集所有文本和图像URL,但并非所有推文都具有图像,因此我想通过解决上述问题来进行匹配。
tweets = browser.find_elements_by_xpath("//span[@class='ctt']")
graph_links = browser.find_elements_by_xpath("//img[@alt='img' and @class='ib']")
这是一项公益计划,旨在帮助失踪人员返回家园。
通过分别收集文本和图像,我认为事后将文本与相关图像进行匹配将是不可能的。我建议采用另一种方法。我将搜索<div class='c'...>
包含文本和可选图像的。一旦有了“容器” DIV,就可以获取文本,查看是否存在图像并将它们放在一起。如果没有所有相关的HTML,您可能需要调整下面的代码,但是它应该使您了解如何实现此目的。
containers = browser.find_elements_by_css_selector("div.c")
for container in containers:
print container.find_element_by_css_selector("span.ctt").text // the tweet text
images = container.find_elements_by_css_selector("img.ib")
if len(images) > 0 // see if the image exists
print images[0].get_attribute("src") // the URL of the image
print "-------------" // separator between tweets
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句