【问题标题】:Can't scrape a certain field from a webpage using requests even when that very field is available in page source无法使用请求从网页中抓取某个字段,即使该字段在页面源中可用
【发布时间】:2021-04-19 18:18:37
【问题描述】:

我正在尝试从网页中抓取电子邮件地址。电子邮件地址在页面源 (ctrl + u) 中可用。但是,我仍然无法使用请求获取它。我得到的只是AttributeError。对此的任何帮助将不胜感激。

webpage link

我目前的尝试:

import requests
from bs4 import BeautifulSoup

link = "https://www.facebook.com/pg/theultimatecollectionco/about/?ref=page_internal"

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36'
    r = s.get(link)
    soup = BeautifulSoup(r.text,"lxml")
    try:
        email = soup.select_one("a[href^='mailto:']").get("href")
    except AttributeError: email = ""
    print(email)

【问题讨论】:

  • 您是否查看过r.text 以确认存在所需的字段?如果网站使用javascript动态添加页面内容,requests模块是看不到的。

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


【解决方案1】:

该页面是在 Javascript 的帮助下构建的,因此仅 BeautifulSoup 无法看到它(selenium 帮助此处)。

最简单的方法是在页面上查找任何mailto: hrefs:

import re
import html
import requests


link = "https://www.facebook.com/pg/theultimatecollectionco/about/?ref=page_internal"

html_doc = requests.get(link).text
for email in re.findall(r'"mailto:([^"]+)"', html_doc):
    print(html.unescape(email))

打印:

support@theultimatecollection.co

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多