数据采集与融合技术第一次作业

发布时间 2023-09-27 11:49:25作者: 兔叽汁汁

作业①

爬取大学排名信息

用requests和BeautifulSoup库方法定向爬取给定网址(http://www.shanghairanking.cn/rankings/bcur/2020 )的数据,屏幕打印爬取的大学排名信息。

import urllib.request
from bs4 import BeautifulSoup
import bs4

def getHTMLText(url):
    try:
        req=urllib.request.Request(url)
        data=urllib.request.urlopen(req)
        data=data.read().decode()
        return data
    except:
        return ""

def fillUnivList(ulist, html):
    soup = BeautifulSoup(html, "html.parser")
    for tr in soup.find('tbody').children:
        if isinstance(tr, bs4.element.Tag):
            a = tr('a')
            tds = tr('td')
            ulist.append([tds[0].text.strip(), a[0].string.strip(), tds[2].text.strip(),tds[3].text.strip(), tds[4].text.strip()])

def printUnivList(ulist, num):
    tplt = "{0: ^10}\t{1: ^10}\t{2: ^12}\t{3: ^8}\t{4: ^10}"
    print(tplt.format("排名", "学校名称","省份", "学校类型","总分"))
    for i in range(num):
        u = ulist[i]
        print(tplt.format(u[0], u[1], u[2], u[3], u[4]))

def main():
    uinfo = []
    url = 'http://www.shanghairanking.cn/rankings/bcur/2020'
    html = getHTMLText(url)
    fillUnivList(uinfo, html)
    printUnivList(uinfo, 30)


main()

运行结果:

心得体会

main()函数是该代码的入口函数,它实现了以下功能:

  • 调用getHTMLText(url)函数获取指定url的网页内容。
  • 调用fillUnivList(ulist, html)函数将网页内容解析并填充到列表ulist中。
  • 调用printUnivList(ulist, num)函数打印指定数量num的学校信息。

通过调用这些函数,可以获取并打印出排名前30的大学信息,包括排名、学校名称、省份、学校类型和总分。

作业②

爬取商品信息

用requests和re库方法设计某个商城(自已选择)商品比价定向爬虫,爬取该商城,以关键词“书包”搜索页面的数据,爬取商品名称和价格。

import urllib.request
from bs4 import BeautifulSoup
import re
import urllib.parse
import w3lib.html
headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.31"}
url="https://search.jd.com/Search?keyword=%E4%B9%A6%E5%8C%85&enc=utf-8&wq=%E4%B9%A6%E5%8C%85&pvid=9bd25fcc2bda47b1bc33a822f0ec8e11" # 京东
def getHtmlText(url,headers):
    req=urllib.request.Request(url,headers=headers)
    html=urllib.request.urlopen(req)
    html=html.read()
    html=html.decode()
    return html

html=getHtmlText(url,headers)
#html文档中去除所有的span标签及其之间的文本内容
html=w3lib.html.remove_tags_with_content(html,which_ones=('span',))
soup = BeautifulSoup(html, "html.parser")
i=0
lis=soup.find_all("li",{"data-sku": re.compile("\d+")})
print("序号\t商品名称\t\t\t\t\t\t\t\t\t\t\t价格")
for li in lis:
    price1=li.find("div",attrs={"class":"p-price"}).find("strong").find("i")
    price = price1.text
    name1=li.find("div",attrs={"class":"p-name"}).find("a").find("em")
    name=name1.text.strip()#找到书包名字及去除头尾所有空格
    i=i+1
    t='\t'
    print(i,t,name,t,price)

运行结果:

心得体会

该代码实现了在京东网站上爬取所需商品的信息。首先通过发送HTTP请求获取网页内容,再利用BeautifulSoup库解析和提取所需的信息,接着使用soup.find_all("li", {"data-sku": re.compile("\d+")})查找所有符合条件的< li>标签,进而获取搜索结果中的商品名称和价格。

作业③

爬取网页图片

爬取一个给定网页( https://xcb.fzu.edu.cn/info/1071/4481.htm)或者自选网页的所有JPEG和JPG格式文件。
输出信息:将自选网页内的所有JPEG和JPG文件保存在一个文件夹中

import os
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse

def save_jpeg_from_url(url, save_folder):
    response = requests.get(url)
    content_type = response.headers["Content-Type"]
    if not content_type.startswith("image/jpeg"):
        return None
    filename = os.path.basename(urlparse(url).path)
    filename = filename.split("?")[0]
    save_path = os.path.join(save_folder, filename)
    # 保存图片
    with open(save_path, "wb") as f:
        f.write(response.content)
    print(f"图片 {save_path} 已保存")

url = "https://xcb.fzu.edu.cn/info/1071/4481.htm"
save_folder = "C:\\Users\\zwl\\Desktop\\picture" #保存图片的文件夹
os.makedirs(save_folder, exist_ok=True)

# 发送HTTP请求并获取网页内容
response = requests.get(url)
content = response.text
soup = BeautifulSoup(content, "html.parser")
img_tags = soup.find_all("img")

for img_tag in img_tags:
    src = img_tag.get("src")
    img_url = urljoin(url, src)
    save_jpeg_from_url(img_url, save_folder)

运行结果:

心得体会

该代码通过发送HTTP请求获取网页内容,并利用BeautifulSoup库解析和提取图片的URL,然后使用requests库下载并保存图片到指定的文件夹。
此外,在设置文件夹位置的时候,由于在路径中的“\”常会被误认为转义字符,故在书写路径的时候应该用“\”来代替。