dun*_*ian 7 python beautifulsoup web-scraping
在给定的.html页面中,我有一个脚本标记,如下所示:
<script>jQuery(window).load(function () {
setTimeout(function(){
jQuery("input[name=Email]").val("name@email.com");
}, 1000);
});</script>
Run Code Online (Sandbox Code Playgroud)
如何使用Beautiful Soup提取电子邮件地址?
plo*_*man 13
我遇到了类似的问题,问题似乎是调用script_tag.text
返回一个空字符串。相反,您必须调用script_tag.string
. 也许这在某些版本的 BeautifulSoup 中发生了变化?
无论如何,@alecxe 的回答对我不起作用,所以我修改了他们的解决方案:
import re
from bs4 import BeautifulSoup
data = """
<body>
<script>jQuery(window).load(function () {
setTimeout(function(){
jQuery("input[name=Email]").val("name@email.com");
}, 1000);
});</script>
</body>
"""
soup = BeautifulSoup(data, "html.parser")
script_tag = soup.find("script")
if script_tag:
# contains all of the script tag, e.g. "jQuery(window)..."
script_tag_contents = script_tag.string
# from there you can search the string using a regex, etc.
email = re.search(r'\.+val\("(.+)"\);', script_tag_contents).group(1)
print(email)
Run Code Online (Sandbox Code Playgroud)
这打印name@email.com
.
ale*_*cxe 11
要在@ Bob的答案中添加更多内容,并假设您还需要script
在HTML中找到可能包含其他script
标记的标记.
我们的想法是定义一个正则表达式,用于定位元素BeautifulSoup
和提取email
值:
import re
from bs4 import BeautifulSoup
data = """
<body>
<script>jQuery(window).load(function () {
setTimeout(function(){
jQuery("input[name=Email]").val("name@email.com");
}, 1000);
});</script>
</body>
"""
pattern = re.compile(r'\.val\("([^@]+@[^@]+\.[^@]+)"\);', re.MULTILINE | re.DOTALL)
soup = BeautifulSoup(data, "html.parser")
script = soup.find("script", text=pattern)
if script:
match = pattern.search(script.text)
if match:
email = match.group(1)
print(email)
Run Code Online (Sandbox Code Playgroud)
印刷品:name@email.com
.
这里我们使用一个简单的正则表达式来表示电子邮件地址,但我们可以更进一步,更严格地对待它,但我怀疑这对于这个问题几乎是必要的.
归档时间: |
|
查看次数: |
14438 次 |
最近记录: |