【问题标题】:Unable to fetch an email link out of some script tag from a webpage无法从网页的某些脚本标签中提取电子邮件链接
【发布时间】:2018-05-10 22:01:59
【问题描述】:

我在 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

顺便说一句,电子邮件链接位于该网页标题profile details 下的第二行。

【问题讨论】:

  • 地址是受保护的,所以确保你得到了像 selemium 这样启用了 javascript 的东西,我假设你是用 urllib / requests 做到的。 items.select_one("dd a[href^='mailto:']") 为 None 的错误信息。

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


【解决方案1】:

您应该查看 Chrome 开发工具的网络标签:

有一段代码:

 <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>

计算结果为&lt;a&gt; 标记,href 属性等于:

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

如果您解码 html 实体,它将是 mailto:Robz@allinthepolish.com,您可以在这里查看:https://mothereff.in/html-entities

因此,一种选择是使用 Selenium 之类的东西作为 cgte proposed。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多