Web Scraper 没有从网站获取完整数据

Web Scraper not getting the full data from a website

我正在尝试抓取 this 网站,为使用 python 的献血营准备数据库。

首先,在尝试从请求或 urllib 获取网站 html 源代码时,有一个 SSl:certificate_verify_error,我通过将 requests.get() 的验证参数设置为 False 绕过了它或为 urllib 创建未经验证的上下文(快速修复),这让我克服了错误,但是当我看到检索到的源 html 代码时,我需要的 table 内容是空的,在网站源他们包含在 tbody 标签中,但我的 requests.get() 命令只获取这些标签,而不是它们之间的内容。我对抓取非常陌生,将不胜感激。泰

from urllib.request import urlopen as uReq
import ssl
from bs4 import BeautifulSoup as soup

my_url = 'https://www.eraktkosh.in/BLDAHIMS/bloodbank/campSchedule.cnt'
sp_context = ssl._create_unverified_context()
uClient = uReq(my_url,context=sp_context)
page_html = uClient.read()
uClient.close()
page_soup=soup(page_html,"html.parser")
table = page_soup.find('tbody')
print (table) #this outputs "<tbody></tbody>"
trow = table.find('tr')
print (trow) #this outputs "None"


第一个打印命令给出

<tbody>
</tbody>

和第二个输出

None 

之所以如此,是因为第一个请求 returns 几乎是空的 html 脚手架。

您在页面上看到的数据正在由后续的 ajax 请求填充。准确地说是这个https://www.eraktkosh.in/BLDAHIMS/bloodbank/nearbyBB.cnt?hmode=GETNEARBYCAMPS&stateCode=-1&districtCode=-1&_=1560150852947

您可以通过右键单击 -> 检查 -> 网络选项卡并重新加载页面来检索此信息。

意见:BeautifulSoup 不需要从此页面提取信息。数据很容易以 json 格式从上面提到的 API 中获得。

希望对您有所帮助。

看看这个 HTTP 调用:

https://www.eraktkosh.in/BLDAHIMS/bloodbank/nearbyBB.cnt?hmode=GETNEARBYCAMPS&stateCode=-1&districtCode=-1&_=1560150750074

这是数据的来源。

您有 2 个选择:

  1. 执行 HTTP 调用并解析响应
  2. 使用无头浏览器并抓取网站。参见 here

使用pandas库将数据保存到csv文件中。

在浏览器 network 选项卡中,您将看到 JSON data responsecampSchedule table 数据。

import requests
import  pandas as pd

url = 'https://www.eraktkosh.in/BLDAHIMS/bloodbank/nearbyBB.cnt?hmode=GETNEARBYCAMPS&stateCode=-1&districtCode=-1&_=1560150855565'
jsonData = requests.get(url, verify=False).json()

campScheduleData = []

for data in jsonData['data']:
    campSchedule = {"Date":"","Time":"","Camp Name":"","Address":"","State":"","District":"",\
                    "Contact":"","Conducted By":"","Organized by":"","Register":""}
    if "<br/>" in data[1]:
        campSchedule['Date'] = data[1].split("<br/>")[0]

    if "href" in data[10]:
        campSchedule['Register'] = "https://www.eraktkosh.in" + data[10].split("href=")[1].split(" ")[0]

    campSchedule['Time'] = data[2]
    campSchedule['Camp Name'] = data[3]
    campSchedule['Address'] = data[4]
    campSchedule['State'] = data[5]
    campSchedule['District'] = data[6]
    campSchedule['Contact'] = data[7]
    campSchedule['Conducted By'] = data[8]
    campSchedule['Organized by'] = data[9]
    campScheduleData.append(campSchedule)

df = pd.DataFrame(campScheduleData)
# it will save csv file in current project directory with campScheduleData.csv file name
df.to_csv("campSchedule.csv")

如果没有安装pandas,请安装:

pip3 install pandas

使用pandas并重新

import requests
import pandas as pd
import urllib3; urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
import re

p1 = re.compile(r"(.*?)<br/>")
p2 = re.compile(r"href='(.*?)'")

def get_url(html, p): 
    if html == 'NA':
        url = html
    else:
        url = 'https://www.eraktkosh.in' + p.findall(html)[0]
    return url

def get_date(html, p): 
    if html == 'NA':
        date_string = html
    else:
        date_string = p.findall(html)[0]
    return date_string

r = requests.get('https://www.eraktkosh.in/BLDAHIMS/bloodbank/nearbyBB.cnt?hmode=GETNEARBYCAMPS&stateCode=-1&districtCode=-1&_=1560150750074', verify = False).json()
df = pd.DataFrame(r['data'])
df[1] = df[1].apply(lambda x: get_date(x, p1))
df[10] = df[10].apply(lambda x: get_url(x, p2))
print(df)