我怎样才能找到包含硒中某些字符串的元素?

时间:2019-05-09 08:25:58

标签: python python-3.x selenium selenium-webdriver

我正在研究一些简单的爬虫,以在Twitter上删除转推计数。 而且我坚持这样做:

<span class="ProfileTweet-actionCountForAria" id="profile-tweet-action-retweet-count-aria-123456789123456789">리트윗 0개</span>

这是我要收集的目标标签。您会看到标签的ID对于每个用户都有一些不同的ID号。所以我试图像这样用find_elements_by_xpath收集那些东西:

retweets = driver.find_elements_by_xpath("//span[@id='profile-tweet-action-retweet-count-area-*'].text")

我认为*在硒的某些地方有效,但在该代码中无效。

因此,简而言之,我如何找到ID为'profile-tweet-action-retweet-count-area'的元素?

感谢您的关注。我找不到这样的问题(也许我没有用正确的问题搜索它,嗯),但是我也找到了很好的参考资料或其他链接!

3 个答案:

答案 0 :(得分:4)

Css选择器将是:

span[id*="profile-tweet-action-retweet-count-aria"]  

或更好的CSS选择器将是:

span[id^='profile-tweet-action-retweet-count-aria']

如果您有多个条目,则可以使用find_elements方法,该方法将为您提供网络元素列表

如果您不想使用CSS选择器,而希望使用xpath:

//span[contains(@id,"profile-tweet-action-retweet-count-aria")]

代码:

list_retweet = driver.find_elements_by_xpath("//span[contains(@id,"profile-tweet-action-retweet-count-aria")]")

for retweet in list_retweet:
  print(retweet.text)

答案 1 :(得分:3)

您可以在xpath或CSS选择器中使用contains()starts-with()方法。

此外,要从元素中获取文本,您必须在.text方法之外使用find_element

XPath:

retweets = driver.find_elements_by_xpath("//span[starts-with(@id,'profile-tweet-action-retweet-count-area-')]")

或者,

retweets = driver.find_elements_by_xpath("//span[contains(@id,'profile-tweet-action-retweet-count-area-')]")

CSS选择器:

retweets = driver.find_elements_by_css_selector("span[@id^='profile-tweet-action-retweet-count-area-']")

或者,

retweets = driver.find_elements_by_css_selector("span[@id*='profile-tweet-action-retweet-count-area-']")

您必须遍历列表以获取所有元素,然后可以使用.text

获取元素的文本。
for retweet in retweets:
    print(retweet.text)

编辑:正如提到的巡游日find_elements_返回一个列表,而.text不适用。另外,CSS选择器不应包含//。我已经相应地更改了代码。

答案 2 :(得分:1)

使用WebdriverWait处理动态元素尝试遵循Xpath或CSS选择器

element=WebDriverWait(driver,30).until(EC.element_to_be_clickable((By.XPATH,'//span[@class="ProfileTweet-actionCountForAria"][starts-with(@id,"profile-tweet-action-retweet-count-aria-")]')))
print(element.text)

OR

element1=WebDriverWait(driver,30).until(EC.element_to_be_clickable((By.CSS_SELECTOR,'span.ProfileTweet-actionCountForAria[id^="profile-tweet-action-retweet-count-aria-"]')))
    print(element1.text)

请注意,您需要使用以下导入。

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By