Beautifulsoup和Panda-帮助修改多页代码 - python

因此,我编写了这段代码来从网站上抓取数据。

import requests
from bs4 import BeautifulSoup
import re

page = requests.get('https://sofifa.com/shortlist/32931')
soup = BeautifulSoup(page.text, 'html.parser')
dados = soup.find_all('a', href=re.compile("/player/"))
capa = soup.find('article')
capa1 = capa.find('div' , {'class': 'card card-border mb-2 fixed-width'})
time = capa1.find('div' , {'class': 'card-title h5'}).string

records = []
for nomes in dados:
    nome = nomes.string
    records.append((nome))

import pandas as pd
from openpyxl import load_workbook

book = load_workbook('Tabela Pipoco 2019.xlsx')
writer = pd.ExcelWriter('Tabela Pipoco 2019.xlsx', engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df = pd.DataFrame(records, columns=[time])
df.to_excel(writer, "Times", index=False, encoding='utf-8', startcol=0)
writer.save()

问题是我想用10个不同的页面来制作!由于缺乏知识,我在jupyter笔记本上编写了10种不同的代码,并全部运行。

唯一会改变代码的东西是这两行:

page = requests.get('https://sofifa.com/shortlist/32931')

df.to_excel(writer, "Times", index=False, encoding='utf-8', startcol=0)

因此,在第一行中,我们将使用特定数字(32931、32882、32589)更改结束数字,依此类推。

在第二行上,startcol=的变化是(第一页为0,第二页为3,第三页为6,依此类推)

如何在单个代码上放置细化?

感谢大伙们

参考方案

编写了3次相同的代码后,请编写函数(c)David Robinson

您可以使用带有两个参数的函数包装代码:urlstartcol,然后在循环中为不同的输入调用此函数。例如:

# Define a function
def your_func_to_avoid_writing_the_same_code_ten_times(url, col):
    page = requests.get(url)  
    # ... missed code for better formatting
    df.to_excel(writer, "Times", index=False, encoding='utf-8', startcol=col)
    writer.save()

url_list = ['https://sofifa.com/shortlist/32931', 'https://sofifa.com/shortlist/32882'] # And so on

# Initialize columns counter
col = 0
# Call the function and update the column
for i in range(len(url_list)): 
    print(your_func_to_avoid_writing_the_same_code_ten_times(url_list[i], col))
    col += 3

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python ThreadPoolExecutor抑制异常 - python

from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…

如何用'-'解析字符串到节点js本地脚本? - python

我正在使用本地节点js脚本来处理字符串。我陷入了将'-'字符串解析为本地节点js脚本的问题。render.js:#! /usr/bin/env -S node -r esm let argv = require('yargs') .usage('$0 [string]') .argv; console.log(argv…