刮擦自己
打开推文的 url,传递给您选择的 HTML 解析器并提取您感兴趣的 XPath。
在以下位置讨论抓取:http://docs.python-guide.org/en/latest/scenarios/scrape/
如果站点的结构始终相同,则可以通过右键单击所需元素,选择“检查”,右键单击检查器中突出显示的行并选择“复制”>“复制 XPath”来获得 XPath。否则,请选择准确定义所需对象的属性。
在你的情况下:
//div[contains(@class, 'permalink-tweet-container')]//strong[contains(@class, 'fullname')]/text()
会给你作者的名字和
//div[contains(@class, 'permalink-tweet-container')]//p[contains(@class, 'tweet-text')]//text()
将为您提供推文的内容。
完整的工作示例:
from lxml import html
import requests
page = requests.get('https://twitter.com/UniteAlbertans/status/899468829151043584')
tree = html.fromstring(page.content)
tree.xpath('//div[contains(@class, "permalink-tweet-container")]//p[contains(@class, "tweet-text")]//text()')
结果:
['Breaking:\n10 sailors missing, 5 injured after USS John S. McCain collides with merchant vessel near Singapore...\n\n', 'https://www.', 'washingtonpost.com/world/another-', 'us-navy-destroyer-collides-with-a-merchant-ship-rescue-efforts-underway/2017/08/20/c42f15b2-8602-11e7-9ce7-9e175d8953fa_story.html?utm_term=.e3e91fff99ba&wpisrc=al_alert-COMBO-world%252Bnation&wpmk=1', u'\xa0', u'\u2026', 'pic.twitter.com/UiGEZq7Eq6']