【发布时间】:2020-02-15 00:02:17
【问题描述】:
想象一下,你在这个 twitter 页面中,你必须获取它的所有 id! https://twitter.com/search?l=fr&q=%23metoo%20since%3A2017-11-06%20until%3A2017-11-09&src=typd
我正在使用 selenium 向下滚动,直到没有剩余,然后将所有 id 保存在一个列表中。
恐怕我的 for 循环并没有保存它们,我做错了什么?
twitter_ids_filename = 'all_ids.json'
id_selector = '.time a.tweet-timestamp'
tweet_selector = 'li.js-stream-item'
ids = []
for day in range(days):
d1 = format_day(increment_day(start, 0))
d2 = format_day(increment_day(start, 1))
url = form_url(d1, d2)
print(url)
print(d1)
driver.get(url)
sleep(delay)
try:
found_tweets = driver.find_elements_by_css_selector(tweet_selector)
increment = 10
while len(found_tweets) >= increment:
print('scrolling down to load more tweets')
driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
sleep(delay)
found_tweets = driver.find_elements_by_css_selector(tweet_selector)
increment += 10
print('{} tweets found, {} total'.format(len(found_tweets), len(ids)))
for tweet in found_tweets:
try:
id = tweet.find_element_by_css_selector(id_selector).get_attribute('href').split('/')[-1]
ids.append(id)
except StaleElementReferenceException as e:
print('lost element reference', tweet)
except NoSuchElementException:
print('no tweets on this day')
【问题讨论】:
-
你为什么不简单地刮一下
data-tweed-id? (这里没有太多关于硒的内容,抱歉) -
我当然可以试试,你能给我举个小例子吗?
-
你是说我应该用漂亮的汤吗?
-
不 - 我正在查看您链接的页面,按 F12,看到适合您的选择器的
<li ..>,然后我在<li ...>中看到<div ...>..<div ...>有一类js-stream-tweet和很多属性。属性之一是data-tweed-id="....."。刮掉它,你就是金子? -
还 ... 使用
ids.append(id.copy())只是为了确保您获得一份副本,而不是对您从拆分中获取的一个元素的引用。