python - 使用 beautifulsoup 提取电子邮件地址(TypeError : 'int' object is not subscriptable)

标签 python web-scraping beautifulsoup web-crawler

我的这部分代码遇到了一个快速问题。基本上我正在使用 beautifulsoup 来废弃一个网站。我只需要从带有类的 div 内的 href 标签中提取电子邮件地址(见下文):

<div class="startup-email-link social-links-startup">
    <a href="mailto:info@example.com">d</a>
</div>

我的代码给了我这个错误:TypeError: 'int' object is not subscriptable

import requests
from bs4 import BeautifulSoup
import re

source_code = requests.get(item_url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")

for link in soup.find('div', {'class': 'startup-email-link'}):
    href = link.find('a')['href']
    print(href)


    #href_final = re.compile('mailto')
    #print(href_final)

最佳答案

soup.find 已经返回单个标签,因此无需对其进行迭代。 您只需获取链接即可

soup.find('div', {'class': 'startup-email-link'}).find('a')['href']

您可能希望使其更加健壮,以防带有类或 anchor 标记的 div 丢失:

div = soup.find('div', {'class': 'startup-email-link'})
if div is None:
    return None
anchor = div.find('a')
if anchor is None:
    return None
return anchor['href']

或者,如果您希望保持更简洁,您可以使用 css 选择器:

selection = soup.select('div.startup-email-linak > a')
if not selection:
    return None
return selection[0]['href']

关于python - 使用 beautifulsoup 提取电子邮件地址(TypeError : 'int' object is not subscriptable),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47575321/

相关文章:

python - 过滤权重低于阈值的边时出现运行时错误 - Networkx

vba - Excel VBA web 源代码 - 如何将多个字段提取到一张表中

Python BeautifulSoup - 在 iframe 中抓取网页内容

python - Beautifulsoup - 抓取除表数据之外的所有内容

python - 如何使用 Chrome 的 webdriver 单击由节点/角度脚本按钮生成的 'Next page'?

python - pandas 或 python 相当于 tidyr complete

python - Django 单元测试 - 客户端登录似乎不起作用

python - Pandas reshape 数据框

python - 在 Scrapy 中重写 parse_start_url() 并将抓取深度限制为 1

javascript - 如何在 Python 中使用 Javascript 对象文字