如何使用 selenium 在 id 中找到包含某些字符串的元素?

Jeo*_*Kim 1 python selenium python-3.x selenium-webdriver

我正在研究一些简单的爬虫来抓取Twitter 上的转发计数。而我坚持这一点:

<span class="ProfileTweet-actionCountForAria" id="profile-tweet-action-retweet-count-aria-123456789123456789">??? 0?</span>
Run Code Online (Sandbox Code Playgroud)

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

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

我认为 * 在 selenium 的某些地方工作,但在该代码中不起作用。

所以,简而言之,我如何找到包含 'profile-tweet-action-retweet-count-area' 的元素?

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

cru*_*dey 5

CSS 选择器将是:

span[id*="profile-tweet-action-retweet-count-aria"]  
Run Code Online (Sandbox Code Playgroud)

或者更好的 css 选择器是:

span[id^='profile-tweet-action-retweet-count-aria']
Run Code Online (Sandbox Code Playgroud)

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

如果您不想要 css 选择器并且想坚持使用 xpath :

//span[contains(@id,"profile-tweet-action-retweet-count-aria")]
Run Code Online (Sandbox Code Playgroud)

代码 :

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

for retweet in list_retweet:
  print(retweet.text)
Run Code Online (Sandbox Code Playgroud)