![](/img/trans.png)
[英]How to loop multiple elements in python selenium (different CSS selectors)
[英]How to scrape elements in Selenium/Python by calling different css selectors at the same time?
我正在嘗試通過集成多個 css 選擇器來 select 加載在網頁中的帖子的標題。 看下面我的過程:
加載相關庫
import time
from selenium import webdriver
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
然后加載我要分析的內容
options = Options()
options.set_preference("dom.push.enabled", False)
browser = webdriver.Firefox(options=options)
browser.get("https://medium.com/search")
browser.find_element_by_xpath("//input[@type='search']").send_keys("international development",Keys.ENTER)
time.sleep(5)
scrolls = 2
while True:
scrolls -= 1
browser.execute_script("window.scrollTo(0, document.body.scrollHeight)")
time.sleep(5)
if scrolls < 0:
break
然后分別獲取每個選擇器的內容,調用 css_selector
titles=browser.find_elements_by_css_selector("h3[class^='graf']")
TitlesList = []
for names in titles:
names.text
TitlesList.append(names.text)
times=browser.find_elements_by_css_selector("time[datetime^='2016']")
Times = []
for names in times:
names.text
Times.append(names.text)
到目前為止一切正常……現在試圖將它們結合在一起,目的是確定 2016 年的唯一選擇
choices = browser.find_elements_by_css_selector("time[datetime^='2016'] and h3[class^='graf']")
browser.quit()
在最后一個片段中,我總是得到一個空列表。
所以我想知道 1)我如何通過同時考慮不同的 css_selector 作為選擇條件來 select 多個元素 2)如果在多個條件下查找的語法與使用不同的方法(如 css_selector 或 x_paths 和 3)鏈接元素相同) 如果有一種方法可以獲取通過調用多個 css 選擇器識別的元素的文本,如下所示:
[pair.text for pair in browser.find_elements_by_css_selector("h3[class^='graf']") if pair.text]
謝謝
首先,我認為你想要做的是獲得任何有時間在 2016 年發布的標題,對嗎?
您正在使用 CSS 選擇器"time[datetime^='2016'] and h3[class^='graf']"
,但這不起作用,因為它的語法無效( and
無效)。 另外,這是 2 個不同的元素,CSS 選擇器只能找到 1 個元素。 在您的情況下,要從另一個元素添加條件,請使用父元素之類的公共元素。
我檢查了該站點,這是您需要查看的 HTML(如果您嘗試使用 2016 年發布的標題)。 這是最小的 HTML 部件,可以幫助您確定您需要獲得什么。
<div class="postArticle postArticle--short js-postArticle js-trackPostPresentation" data-post-id="d17220aecaa8"
data-source="search_post---------2">
<div class="u-clearfix u-marginBottom15 u-paddingTop5">
<div class="postMetaInline u-floatLeft u-sm-maxWidthFullWidth">
<div class="u-flexCenter">
<div class="postMetaInline postMetaInline-authorLockup ui-captionStrong u-flex1 u-noWrapWithEllipsis">
<div
class="ui-caption u-fontSize12 u-baseColor--textNormal u-textColorNormal js-postMetaInlineSupplemental">
<a class="link link--darken"
href="https://provocations.darkmatterlabs.org/reimagining-international-development-for-the-21st-century-d17220aecaa8?source=search_post---------2"
data-action="open-post"
data-action-value="https://provocations.darkmatterlabs.org/reimagining-international-development-for-the-21st-century-d17220aecaa8?source=search_post---------2"
data-action-source="preview-listing">
<time datetime="2016-09-05T13:55:05.811Z">Sep 5, 2016</time>
</a>
</div>
</div>
</div>
</div>
</div>
<div class="postArticle-content">
<a href="https://provocations.darkmatterlabs.org/reimagining-international-development-for-the-21st-century-d17220aecaa8?source=search_post---------2"
data-action="open-post" data-action-source="search_post---------2"
data-action-value="https://provocations.darkmatterlabs.org/reimagining-international-development-for-the-21st-century-d17220aecaa8?source=search_post---------2"
data-action-index="2" data-post-id="d17220aecaa8">
<section class="section section--body section--first section--last">
<div class="section-divider">
<hr class="section-divider">
</div>
<div class="section-content">
<div class="section-inner sectionLayout--insetColumn">
<h3 name="5910" id="5910" class="graf graf--h3 graf--leading graf--title">Reimagining
International Development for the 21st Century.</h3>
</div>
</div>
</section>
</a>
</div>
</div>
time
和h3
都在一個大div
中,其中 class 為postArticle
。 文章包含發布時間和標題,因此獲取 2016 年發布的整篇文章div
是否有意義?
使用 XPATH 功能更強大且更易於編寫:
div
的postArticle--short
名稱: article_xpath = '//div[contains(@class, "postArticle--short")]'
time
標簽2016
: //time[contains(@datetime, "2016")]
讓我們將它們結合起來。 我想獲取包含類名為2016
的time
標簽的文章div
:
article_2016_xpath = '//div[contains(@class, "postArticle--short")][.//time[contains(@datetime, "2016")]]'
article_element_list = driver.find_elements_by_xpath(article_2016_xpath)
# now let's get the title
for article in article_element_list:
title = article.find_element_by_tag_name("h3").text
我還沒有測試代碼,只有 xpath。 您可能需要調整代碼以在您身邊工作。
順便說一句,使用find_element...
不是一個好主意,嘗試使用顯式等待: https://selenium-python.readthedocs.io/waits.html
這將幫助您避免愚蠢的time.sleep
等待並提高您的應用程序性能,並且您可以很好地處理錯誤。
僅當您已經找到元素並且需要在其中找到子元素時才使用find_element...
比如本例中如果要查找文章,我會通過顯式等待查找,然后在找到元素后,我會使用find_element...
查找子元素h3
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.