python - 从 twitter 的 selenium 元素中获取推文文本
问题描述
我正在尝试从 Twitter 中的趋势标签中抓取推文。我试图在推文中找到文本的 xpath,但它不起作用。
browser = webdriver.Chrome('/Users/Suraj/Desktop/twitter/chromedriver')
url = 'https://twitter.com/search?q=%23'+'Swastika'+'&src=trend_click'
browser.get(url)
time.sleep(1)
以下代码没有给出任何结果。
browser.find_elements_by_xpath('//*[@id="tweet-text"]')
我能够在哪里找到的其他内容:
browser.find_elements_by_css_selector("[data-testid=\"tweet\"]") # works
browser.find_elements_by_xpath("/html/body/div[1]/div/div/div[2]/main/div/div/div/div[1]/div/div[2]/div/div/section/div/div/div/div/div/div/article/div/div/div/div[2]/div[2]/div[1]/div/div") # works
我想知道如何从推文中选择文本。
解决方案
您可以使用 Selenium 来抓取 twitter,但将 twitter API 与 tweepy 一起使用会更容易/更快/高效。您可以在此处注册开发者帐户:https ://developer.twitter.com/en/docs
注册后,获取访问密钥并像这样使用 tweepy:
import tweepy
# connects to twitter and authenticates your requests
auth = tweepy.OAuthHandler(TWapiKey, TWapiSecretKey)
auth.set_access_token(TWaccessToken, TWaccessTokenSecret)
# wait_on_rate_limit prevents you from requesting too many times and having twitter block you
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
# loops through every tweet that tweepy.Cursor pulls -- api.search tells cursor
# what to do, q is the search term, result_type can be recent popular or mixed,
# and the max_id/since_id are snowflake ids which are twitters way of
# representing time and finally count is the maximum amount of tweets you can return per request.
for tweet in tweepy.Cursor(api.search, q=YourSearchTerm, result_type='recent', max_id=snowFlakeCurrent, since_id=snowFlakeEnd, count=100).items(500):
createdTime = tweet.created_at.strftime('%Y-%m-%d %H:%M')
createdTime = dt.datetime.strptime(createdTime, '%Y-%m-%d %H:%M').replace(tzinfo=pytz.UTC)
data.append(createdTime)
此代码是一个脚本示例,该脚本从 YourSearchTerm 最近的推文中提取 500 条推文,然后将每个推文的创建时间附加到列表中。您可以在此处查看 tweepy 文档:http: //docs.tweepy.org/en/latest/
您使用 tweepy.Cursor() 提取的每条推文都将具有许多属性,您可以选择这些属性并将其附加到列表中或执行其他操作。尽管可以使用 Selenium 抓取 twitter,但确实不建议这样做,因为它会非常慢,而 tweepy 返回结果只需几秒钟。
推荐阅读
- ios - 将 adMob 添加到现有的 Firebase 应用程序
- excel - 代码在一张纸上运行(复制和粘贴),但从另一张纸上运行时不执行任何操作
- c++ - 获取嵌套的 JSON 成员而不直接获取每个中间对象
- assembly - 分配后返回不同值的内存地址
- asp.net - Crystal Reports 抑制子报表上的问题
- python - 在 Skulpt 中的 turtle.color() 中传递一个标量有什么影响?
- reactjs - 在具有 zIndex 的绝对定位容器中未触发的可触摸压力机(用于下拉菜单)
- matlab - 如何将向量转换为矩阵
- dns - Route53:SOA记录、NS记录存放在哪里?
- amazon-web-services - 如何在 AWS Lambda node.js 中为 updateitem dynamodb 创建运行时参数