python - 在使用偏移而不是页面来更改其内容列表的网站上抓取多个页面的最佳方法是什么

标签 python html web-scraping beautifulsoup offset

我想抓取这个网站:https://repositori.usu.ac.id/handle/123456789/165?offset=0
当链接上的偏移量设置为0时,内容如下所示: Website When Offset is 0
而当偏移量设置为1时,内容如下所示:Website When Offset is 1

请注意,列表最上面的一项已被删除并更改为下面的一项。
该网站最多只显示 20 个列表,并且每 1 个偏移量会从最顶部删除 1 个列表,并将其替换为下面的列表。因此我们需要 20 偏移量来完全更改内容列表。

我想制作一个网络抓取程序来抓取所述网站。但当我需要抓取 20 多个不同的列表时,我发现很困难。由于偏移量的工作方式与页面不同,因此在进行多个范围抓取时,我总是抓取同一列表的两到三次,这并不理想。
这是我的代码:(理想情况下需要输入的偏移量是0,但它不让我并且总是输入1。我不知道如何将默认偏移量设置为0)

from unittest import result
import requests
from bs4 import BeautifulSoup
import csv
import urllib3.request

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


fakdep = '165'  
offset = input('Please enter number of offset:')
url = 'https://repositori.usu.ac.id/handle/123456789/{}?offset={}0'.format(fakdep,offset)
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'
    }

datas = []
count_offset = 0

for offset in range(1,6):
    count_offset+=1
    print('Scraping Page:', count_offset)
    result = requests.get(url+str(offset), verify=False)
    #print(result)
    soup = BeautifulSoup(result.text, 'html.parser')
    items = soup.find_all('li','ds-artifact-item')
    for it in items:
        author = it.find('span','author h4').text
        title = ''.join(it.find('a',href=True).text.strip().replace('/n', ' '))
        year = it.find('span','date').text
        abstract = ''.join(it.find('div','artifact-abstract').text.strip().replace('/n', ' '))
        link = it.find('a')['href']        
        datas.append([author, title, year, abstract, "https://repositori.usu.ac.id"+link])

kepala = ['Author', 'Title', 'Year', 'Abstract', 'Link']
thewriter = csv.writer(open('results/{}_{}.csv'.format(fakdep,offset), 'w', newline=''),delimiter=";")
thewriter.writerow(kepala)
for d in datas: thewriter.writerow(d)

我还没有找到另一种方法来解决这个问题。
我感谢任何形式的帮助。
谢谢!

最佳答案

您只能在for循环内使用偏移量进行分页 .每页又称为偏移量的增量为20,总偏移量=598 。所以分页逻辑是(0,598,20)。您可以使用 pandas DataFrame 将数据存储为 csv 格式,因为它更具体,也是在本地系统中保存数据的最简单且可靠的方法。

import requests
from bs4 import BeautifulSoup
import urllib3.request
import pandas as pd
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

url = 'https://repositori.usu.ac.id/handle/123456789/165?offset={offset}'
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'
    }

datas = []

for offset in range(0,598,20):
    result = requests.get(url.format(offset=offset), verify=False)
    soup = BeautifulSoup(result.text, 'html.parser')
    items = soup.find_all('li','ds-artifact-item')
    for it in items:
        author = it.find('span','author h4').text
        title = ''.join(it.find('a',href=True).text.strip().replace('/n', ' '))
        year = it.find('span','date').text
        abstract = ''.join(it.find('div','artifact-abstract').text.strip().replace('/n', ' '))
        link = it.find('a')['href']        
        datas.append([author, title, year, abstract, "https://repositori.usu.ac.id"+link])

kepala = ['Author', 'Title', 'Year', 'Abstract', 'Link']

df = pd.DataFrame(datas,columns=kepala)
df.to_csv('out.csv',index=False)
#print(df)

输出:

  Author  ...                                               Link
0     Angin, Tifany Perangin  ...  https://repositori.usu.ac.id/handle/123456789/...
1    Fandya, Rafif Akhmad Al  ...  https://repositori.usu.ac.id/handle/123456789/...
2         Rizkiansyah, Halqi  ...  https://repositori.usu.ac.id/handle/123456789/...
3      Sitompul, Ummi Balqis  ...  https://repositori.usu.ac.id/handle/123456789/...
4       Manalu, Hari Purnomo  ...  https://repositori.usu.ac.id/handle/123456789/...
..                       ...  ...                                                ...
593                 Caroline  ...  https://repositori.usu.ac.id/handle/123456789/...
594              Afif, Ridho  ...  https://repositori.usu.ac.id/handle/123456789/...
595    Putra, M.Ananda Rizki  ...  https://repositori.usu.ac.id/handle/123456789/...
596          Ignasius, Angga  ...  https://repositori.usu.ac.id/handle/123456789/...
597     Tarigan, Modalina Br  ...  https://repositori.usu.ac.id/handle/123456789/...

[598 rows x 5 columns]

关于python - 在使用偏移而不是页面来更改其内容列表的网站上抓取多个页面的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73935945/

相关文章:

html - 仅用一种形式替换它

javascript - 使用 javascript,我如何判断 DOM 中的 HTML 对象是否不在 HTML 源代码中?

javascript - 使用 python 抓取验证码

java - 如何使用Java进程运行python管道命令?

python - 为什么这个 for 循环会乘以所有的东西?

javascript - 使用 getElementById 一次指定 2 个操作

python - 使用scrapy爬取bbs时Twist失败

python - 打印带有足够前导空格的字符串?

python - 实现数值求解微分方程的初始条件

c# - 使用 HTML Agility Pack 获取图像旁边的文本?