我需要解析页面上所有父元素中的一些子元素。在
创建页面上所有文章的列表
article_elements = driver.find_elements_by_tag_name('article')
并在绑定后获取for循环中的子元素并将所有结果追加到列表中
^{pr2}$循环结束后,我得到了40倍于同一篇文章的meta(第一篇文章的)
{'share count': u'66', 'points': u'53 points', 'title': u'25+ Random Acts Of Genius Vandalism'}
{'share count': u'66', 'points': u'53 points', 'title': u'25+ Random Acts Of Genius Vandalism'}
{'share count': u'66', 'points': u'53 points', 'title': u'25+ Random Acts Of Genius Vandalism'}
{'share count': u'66', 'points': u'53 points', 'title': u'25+ Random Acts Of Genius Vandalism'}
... 40 times
我的全部代码
# coding: utf8
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Chrome()
driver.set_window_size(1024,768)
driver.get('http://www.boredpanda.com/')
time.sleep(2)
meta_info_list = []
article_elements = driver.find_elements_by_tag_name('article')
for article in article_elements:
title = article.find_element_by_xpath('//article/h2').text
share_count = article.find_element_by_xpath('//footer/div/a/span').text
poinst = article.find_element_by_xpath('//footer/div[2]/div[1]/div[3]').text
meta_info_list.append({'title':title, 'share count':share_count, 'points':poinst})
for list in meta_info_list:
print(list)
循环中的XPath表达式必须以点开头才能特定于上下文:
作为补充说明,您可以使用列表理解来缩短代码:
^{pr2}$相关问题 更多 >
编程相关推荐