【问题标题】:python requests only returning empty sets when scraping .htm pagepython请求在抓取.htm页面时只返回空集
【发布时间】:2017-12-12 19:31:51
【问题描述】:

我正在尝试抓取 .htm 链接,但无法让我的脚本返回除 '[]' 之外的任何内容。

链接 = https://www.forwardhealth.wi.gov/WIPortal/StaticContent/Member/caseloads/481-caseload.htm

import requests
from bs4 import BeautifulSoup as bs

link = 'https://www.forwardhealth.wi.gov/WIPortal/StaticContent/Member/caseloads/481-caseload.htm'
headers = {'User-Agent':'Mozilla/5.0'}
r = requests.get(link, headers=headers)
soup = bs(r.text, 'lxml')      #I've tried other html parsers in here as well as r.content

我认为问题在于我尝试与页面交互(可能编码不正确?)。上述格式是我过去一直设置任何网络抓取的方式,并且没有遇到任何我无法解决的问题。最突出的是当我打电话给r.contentr.text 时,我得到的回复似乎很陌生:

'<HTML>\r\n<HEAD>\r\n<TITLE>481-caseload</TITLE>\r\n<META NAME="GENERATOR" CONTENT="Microsoft FrontPage 5.0">\r\n<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">\r\n</HEAD>\r\n\r\n<FRAMESET ROWS="*,48" FRAMESPACING="0" FRAMEBORDER="no" BORDER="0">\r\n<FRAME NAME="ReportArea" SRC="481-caseload/by_county_tribe/by_county_tribe.htm"\r\n MARGINWIDTH="0" MARGINHEIGHT="0" SCROLLING="no" FRAMEBORDER="0" NORESIZE>\r\n<FRAMESET COLS="*" FRAMESPACING="0" FRAMEBORDER="0" BORDER="0">\r\n<FRAME NAME="ReportLinks" SRC="481-caseload/DocLinks.htm" FRAMEBORDER="0" MARGINWIDTH="2" MARGINHEIGHT="3" scrolling="auto">\r\n</FRAMESET></FRAMESET></HTML>'

这让我觉得我的脚本没有正确编写来处理上面的任何内容。我以前从未见过“Microsoft FrontPage 5.0”,不知道这是否可能是我的代码被抛弃的原因。我尝试通过更改r.encoding = #encoding here 来强制编码。任何指导都会有所帮助。

【问题讨论】:

    标签: python html web-scraping beautifulsoup python-requests


    【解决方案1】:

    这是因为该页面由多个嵌套的iframes 组成 - 基本上,当加载主“容器”页面时,浏览器会加载具有自己的 URL 的单独页面。使用浏览器开发者工具检查页面并查看您想要的内容位于iframe 中。

    本页主要内容来自this url

    In [1]: import requests
    
    In [2]: from bs4 import BeautifulSoup
    
    In [3]: url = "https://www.forwardhealth.wi.gov/WIPortal/StaticContent/Member/caseloads/481-caseload/by_county_tribe/0.htm"
    
    In [4]: response = requests.get(url)
    
    In [5]: soup = BeautifulSoup(response.content, "lxml")
    
    In [6]: soup.select_one("td.s2").get_text()
    Out[6]: 'Wisconsin Medicaid'
    

    【讨论】:

      猜你喜欢
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-08
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 2018-06-26
      • 2018-03-22
      相关资源
      最近更新 更多