python - 如何从大多数网站获取 Twitter 链接 - Python

标签 python regex beautifulsoup

我正在构建一个网络爬虫,它可以扫描网站中的 Twitter 链接。我对 BeautifulSoup 很陌生,我过得很艰难。我尝试过使用正则表达式来解析页面的整个 HTML,但是效果不如漂亮的汤。目前,我的代码获取一个网站并尝试解析它以获取 Twitter URL。

当然,我知道这并不总是有效,但现在所有内容都以 None 返回,并且永远不会返回 Twitter 链接,尽管我知道这些网站包含它们。另外,曾经有 5 个链接我通常也会收到错误:

AttributeError: 'NoneType' object has no attribute 'group'

我专门对其进行了测试。我真的不认为这应该这么难,但考虑到已经如此,我想我一定是在 beautifulsoup 上犯了一个巨大的根本缺陷,而我只是没有看到。有任何想法吗?

def twitter_grab(url):
    hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11', 
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
    'Accept-Encoding': 'none',
    'Accept-Language': 'en-US,en;q=0.8',
    'Connection': 'keep-alive'}
    req = urllib2.Request(url, headers=hdr)
    response = urllib2.urlopen(req)
    soup = BeautifulSoup(response, 'html.parser')
    links = soup.find_all('a' or 'li')
    for tag in links:
        link = tag.get('href', None)
        if link is not None:
            text = re.search(r'http://www\.twitter\.com/(\w+)', link)
            if text is not None:
                handle = text.group(0)
                print handle
                return(handle)

最佳答案

您通常不需要在 beautiful soup 中使用正则表达式,因为每个部分都是可访问的,BS 将每个标签作为字典返回,因此您可以将参数作为键访问:

handles = [ a["href"] for a in soup.find_all("a", href=True) if("twitter" in a["href"])]

这将返回所有已超链接的部分。如果某个网站由于某种原因没有写 <a/>标记这个会错过它。

关于python - 如何从大多数网站获取 Twitter 链接 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46005071/

相关文章:

python - BeautifulSoup:获取特定表的内容

python - 压缩 Django 迁移时的循环依赖

python - 将字符串元组转换为字典

python - FTPSHook Airflow(数据通道需要 522 SSL/TLS)

python - 拆分名称列表,其中两个名字可能有共同的姓氏

c# - 使用正则表达式删除sql脚本文件中的所有GO

javascript - 这种 sanitizer 容易受到 XSS 攻击吗?

python - 如何使用 BeautifulSoup 单击页面上的某个位置

python - 怎样才能让蛇继续移动呢?

python - 创建列的滚动总和,该列在 python pandas 中按周滚动分组