使用硒来刮除id\u str obj

2024-04-23 12:01:18 发布

您现在位置:Python中文网/ 问答频道 /正文

使用python中的Selenium库,我目前正在从twitter搜索结果页中抓取内容:https://twitter.com/search?q=twinkie&src=typd&lang=en

Selenium库具有以下函数来标识我们要获取的内容:

find_elements_by_name
find_elements_by_xpath
find_elements_by_link_text
find_elements_by_partial_link_text
find_elements_by_tag_name
find_elements_by_class_name
find_elements_by_css_selector

我要获取的特定对象称为id\u str,它是一个特定于每个帐户的唯一数字字符串。我一直很难弄清楚如何抓住这个特殊的物体。你知道吗

由于每个元素的长度,我不想在这里直接复制所有的html代码,但是我注意到所有的id\u str前面都有:

<div class="tweet js-stream-tweet js-actionable-tweet js-profile-popup-actionable dismissible-content
   original-tweet js-original-tweet


   has-cards  has-content

你建议我使用哪个函数来获取id\u str。最理想的情况是,我希望与网页代码有足够的关系,这样我就能够自己识别其他对象--我应该复习哪些主题来更好地理解?我对编码还是比较陌生的。你知道吗

非常感谢你阅读了大家的文章


Tags: 函数textnameid内容byseleniumjs
3条回答

假设您希望在共享的div元素的“data reply to users json”属性中获取“id\u str”键的值,请尝试以下操作:

from selenium import webdriver
import ast

driver = webdriver.Chrome()
driver.get('https://twitter.com/search?q=twinkie&src=typd&lang=en')
tweets = driver.find_elements_by_xpath("//div[contains(@class, 'tweet js-stream-tweet js-actionable-tweet js-profile-popup-actionable dismissible-content')]")
for tweet in tweets:
    print(ast.literal_eval(tweet.get_attribute('data-reply-to-users-json'))[0]['id_str'])

这将打印所有“id\u str”值。你知道吗

如果您知道xpath,请使用xpath。否则使用css。你知道吗

find_elements_by_css_selector('*[id_str]')

你可以简化,因为你只是在那些tweets的用户id的现有属性之后

from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://twitter.com/search?q=twinkie&src=typd&lang=en')
tweets = [tweet.get_attribute('data-user-id') for tweet in driver.find_elements_by_css_selector('[data-reply-to-users-json]')]
print(tweets)
#driver.quit()

相关问题 更多 >