2023数据采集与融合技术实践作业一

发布时间 2023-09-25 18:21:06作者: 溯-

作业①:

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

本题我们使用requests和beautifulsoup来获取网页内容并提取所要的信息。代码如下:

import requests
from bs4 import BeautifulSoup
import bs4
try:
    url = "https://www.shanghairanking.cn/rankings/bcur/2020"
    response = requests.get(url)
    response.encoding=response.apparent_encoding
    data = response.text
    soup = BeautifulSoup(data, "html.parser")
    table_body = soup.find('tbody')
    rows = table_body.find_all('tr')
    data_list = []
    for row in rows:
        if isinstance(row, bs4.element.Tag):
            link = row.find('a')
            table_data = row.find_all('td')
            data_list.append([table_data[0].text.strip(), link.text.strip(), table_data[2].text.strip(),
                              table_data[3].text.strip(), table_data[4].text.strip()])
    output_format = "{rank:^10}\t{school_name:^10}\t{province:^12}\t{school_type:^12}\t{total_score:^10}"
    print(output_format.format(rank="排名", school_name="学校名称", province="省份", school_type="学校类型",
                               total_score="总分"))
    for item in data_list[:30]:
        print(output_format.format(rank=item[0], school_name=item[1], province=item[2], school_type=item[3],
                                   total_score=item[4]))
except Exception as err:
    print(err)

运行结果如下:
image
image

2、心得体会

通过这个作业,我对requests库和beautifulsoup库更加了解,并且能够使用相关函数完成一定的任务。

作业②:

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

本题我们使用requests库相关函数和正则表达式来获取商品名称和价格。代码如下:

import re
import requests
headers = {
    'user-agent': 'Mozilla/5.0',
}
try:
    keyword = "书包"
    url = f"https://re.jd.com/search?keyword={keyword}&enc=utf-8"
    product_list = []
    response = requests.get(url, headers=headers)
    response.encoding = response.apparent_encoding
    data = response.text
    price_list = re.findall(r'"sku_price":"[\s\S]*?"', data)
    title_list = re.findall(r'"ad_title_text":"[\s\S]*?"', data)
    for i in range(len(title_list)):
        price = eval(price_list[i].split(":")[1])
        name = eval(title_list[i].split(":")[1])
        product_list.append([i + 1, price, name])
    print("{:^5}\t{:^10}\t{:^20}".format("序号", "价格", "商品名称"))
    for product in product_list:
        print("{:^5}\t{:^10}\t{:^20}".format(product[0], product[1], product[2]))
except Exception as err:
    print(err)

运行结果如下:
image
image
image

2)、心得体会

通过这个作业,我对requests库的使用有了进一步的了解,对如何使用requests库相关函数更加熟悉。同时我对正则表达式的使用更加了解,能够使用正则表达式提取需要的内容

作业③:

1)、要求:爬取一个给定网页( https://xcb.fzu.edu.cn/info/1071/4481.htm)或者自选网页的所有JPEG和JPG格式文件

本题我们使用beautifulsoup找到照片所对应的链接,然后打开照片链接,分别把链接里面的内容写入到文件当中。代码如下:

import requests
from bs4 import BeautifulSoup
headers = {
    'user-agent': 'Mozilla/5.0',
}
try:
    url = "https://xcb.fzu.edu.cn/info/1071/4481.htm"
    response = requests.get(url, headers=headers)
    response.encoding = response.apparent_encoding
    data = response.text
    soup = BeautifulSoup(data, 'html.parser')
    img_tags = soup.find_all('img')
    for img in img_tags:
        link = img['src']
        if link.startswith('/'):
            link = "https://xcb.fzu.edu.cn" + link
        a = requests.get(link)
        with open("C:/Users/19350/Desktop/img1/" + str(img_tags.index(img) + 1) + ".jpg", 'wb') as f:
            f.write(a.content)
except Exception as err:
    print(err)

运行结果如下:
image

2)、心得体会

通过这个作业,我对requests和beautifulsoup的使用更加熟练,能够使用相关函数来获取图片。