python - 无法从网页的某些脚本标记中获取电子邮件链接

标签 python python-3.x web-scraping beautifulsoup

我已经用 python 编写了一个脚本来从网页中抓取电子邮件地址,但我无法做到。电子邮件地址位于 script 标记内,我无法打破该障碍来获取内容。任何帮助实现这一点将不胜感激。

Webpage link

到目前为止我已经尝试过:

import requests
from bs4 import BeautifulSoup

url = "replace_with_link_above"

res = requests.get(url)
soup = BeautifulSoup(res.text, "lxml")
for items in soup.select(".profile-right-info"):
    email = items.select_one("dd a[href^='mailto:']")['href']
    print(email)

执行后出现以下错误:

    email = items.select_one("dd a[href^='mailto:']")['href']
TypeError: 'NoneType' object is not subscriptable

顺便说一句,电子邮件链接位于该网页中标题个人资料详细信息下的第二行。

最佳答案

您应该查看 Chrome 开发工具的“网络”选项卡:

enter image description here

有一段代码:

 <script language='JavaScript' type='text/javascript'>
 <!--
 var prefix = 'm&#97;&#105;lt&#111;:';
 var suffix = '';
 var attribs = '';
 var path = 'hr' + 'ef' + '=';
 var addy99716 = "R&#111;bz" + '&#64;';
 addy99716 = addy99716 + '&#97;ll&#105;nth&#101;p&#111;l&#105;sh' + '&#46;' + 'c&#111;m';
 document.write( '<a ' + path + '"' + prefix + addy99716 + suffix + '"' + attribs + '>' );
 document.write( addy99716 );
 document.write( '<\/a>' );
 //-->
 </script>

其计算结果为<a>标记为 href属性等于:

m&#97;&#105;lt&#111;:R&#111;bz&#64;&#97;ll&#105;nth&#101;p&#111;l&#105;sh&#46;c&#111;m

这将是 mailto:<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a2f0cdc0d8e2c3cececbccd6cac7d2cdcecbd1ca8cc1cdcf" rel="noreferrer noopener nofollow">[email protected]</a>如果您解码 html 实体,您可以在这里检查:https://mothereff.in/html-entities

因此,一种选择是使用像 Selenium 这样的东西 cgte proposed .

另一个选项是获取 <dd> 的内容标记,解析 js 代码,然后使用 node 运行它可执行文件(如果不在沙箱中运行它可能会很危险)或手动评估。 Selenium 的选项似乎简单得多。

关于python - 无法从网页的某些脚本标记中获取电子邮件链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50282121/

相关文章:

python - Scrapy 使用错误的编码,从网页向 JSON 添加额外的 html 标签

python - Pandas 合并两个数据框,一个包含另一个数据框的列值

python - 在下面的代码中解释打印策略

python - Python 中 BeautifulSoup 中的 .find()

javascript - 该域名是否可用或已被占用?在 Google 表格应用脚本中

Python3 : BeautifulSoup4 not returning expected value

python - 如何在 BigQuery Web UI 中创建隐藏数据集,同时保持数据工作室连接可用?

python - 将列表列表和 "distributing"元素从另一个列表获取到子列表的 Pythonic 方法是什么?

求矩阵转置的Python代码

python - 创建一个图形,其中节点为带有文本的圆圈