【问题标题】:Hashtags python html标签 python html
【发布时间】:2018-01-08 08:23:45
【问题描述】:

我想从给定网站中提取所有主题标签: 例如,“我喜欢#stack overflow,因为#people 非常#helpful!” 这应该将 3 个主题标签拉到一个表中。 在我的目标网站中,有一个带有#tag 描述的表格 所以我们可以找到#love 这个标签谈论爱

这是我的作品:

    #import the library used to query a website
    import urllib2
    #specify the url
    wiki = "https://www.symplur.com/healthcare-hashtags/tweet-chats/all"
    #Query the website and return the html to the variable 'page'
    page = urllib2.urlopen(wiki)
    #import the Beautiful soup functions to parse the data returned from the 
     website
    from bs4 import BeautifulSoup
    #Parse the html in the 'page' variable, and store it in Beautiful Soup 
    format
     soup = BeautifulSoup(page, "lxml")
    print soup.prettify()
    s = soup.get_text()
    import re
     re.findall("#(\w+)", s)

我的输出有问题: 第一个是输出如下所示: [u'eeeeee', u'333333', 你'222222', 你'222222', 你'222222', 你'222222', 你'222222', 你'222222', 你'222222', u'AASTGrandRoundsacute'

输出将 Hashtag 与描述中的第一个单词连接起来。如果我与我在输出为“lovethis”之前调用的示例进行比较。

如何只提取主题标签后的一个单词。

谢谢

【问题讨论】:

标签: python html beautifulsoup lxml hashtag


【解决方案1】:

我认为没有必要使用regex 来解析从页面中获取的文本,您可以使用BeautifulSoup 本身。我在下面的代码中使用的是 Python3.6,只是为了显示整个代码,但重要的一行是hashtags = soup.findAll('td', {'id':'tweetchatlist_hashtag'})。注意表中的所有标签都有td标签和id属性= tweetchatlist_hashtag,所以调用.findAll是这里的方法:

import requests
import re
from bs4 import BeautifulSoup

wiki = "https://www.symplur.com/healthcare-hashtags/tweet-chats/all"
page = requests.get(wiki).text
soup = BeautifulSoup(page, "lxml")

hashtags = soup.findAll('td', {'id':'tweetchatlist_hashtag'})

现在让我们看看列表的第一项:

>>> hashtags[0]
<td id="tweetchatlist_hashtag" itemprop="location"><a href="https://www.symplur.com/healthcare-hashtags/aastgrandrounds/" title="#AASTGrandRounds">#AASTGrandRounds</a></td>

所以我们看到我们真正想要的是atitle属性的值:

>>> hashtags[0].a['title']
'#AASTGrandRounds'

继续使用列表理解获取所有主题标签的列表:

>>> lst = [hashtag.a['title'] for hashtag in hashtags]

如果你不使用列表推导语法,上面的行是这样的:

>>> lst = []
>>> for hashtag in hashtags:
    lst.append(hashtag.a['title'])

lst 然后是所需的输出,请参阅列表的前 20 项:

>>> lst[:20]
['#AASTGrandRounds', '#abcDrBchat', '#addictionchat', '#advocacychat', '#AetnaMyHealthy', '#AlzChat', '#AnatQ', '#anzOTalk', '#AskAvaility', '#ASPChat', '#ATtalk', '#autchat', '#AXSChat', '#ayacsm', '#bcceu', '#bccww', '#BCSM', '#benurse', '#BeTheDifference', '#bioethx']

【讨论】:

  • 谢谢,运行您的解决方案我收到错误:ConnectionError: HTTPSConnectionPool(host='www.symplur.com', port=443): retries with url: /healthcare-hashtags/tweet-chats /all(由 NewConnectionError(' 引起):无法建立新连接:[Errno 10060] Une tentative de connexion a \xe9chou\xe9 car le parti connect\xe9 n \x92a pas r\xe9pondu convenablement au-del\xe0 d\x92une certaine dur\xe9e ou une connexion \xe9tablie a \xe9chou\xe9 car l\x92h\xf4te de connexion n\x92a pas r\xe9pondu',))跨度>
  • 代理问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-24
  • 2011-02-26
  • 1970-01-01
  • 1970-01-01
  • 2019-08-12
  • 2020-03-08
  • 2021-02-02
相关资源
最近更新 更多