python - “TypeError:open() 在我的解析代码中得到了一个意外的关键字参数‘newline’”
问题描述
所以这是我的解析代码
import requests
from bs4 import BeautifulSoup
import csv
import codecs
CSV = 'cards.csv'
HOST = 'https://minfin.com.ua'
URL = 'https://minfin.com.ua/cards/'
HEADERS = {
'accept': 'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'
}
def get_html(url,params = ''):
r = requests.get(url,headers = HEADERS,params = params)
return r
def get_content(html):
soup = BeautifulSoup(html,'html.parser')
items = soup.find_all('div', class_= 'product-item product-item-holder')
cards = []
for item in items:
cards.append(
{
'title': item.find('div',class_ = 'title').get_text(strip = True),
'link_product' : HOST + item.find('div', class_ = 'title').find('a').get('href'),
'brand' : item.find('div', class_ = 'brand').get_text(strip = True),
'card_image': HOST + item.find('div',class_ = 'image').find('img').get('src')
}
)
return cards
def save_doc(items,path):
with codecs.open(path, 'w','utf-16',newline = '') as file:
writer = csv.writer(file,delimiter = ';')
writer.writerow(['Название Продукта','Ссылка на Продукт','Название Банка','Картинка'])
for item in items:
writer.writerow([item['title'],item['link_product'],item['brand'], item['card_image']])
def parse():
PAGE = input("Сколько страниц спарсить: ")
PAGE = int(PAGE.strip())
html = get_html(URL)
if html.status_code == 200:
cards = []
for page in range(1,PAGE):
print(f'Парсим страницу: {page}')
html = get_html(URL,params = {'page' : page})
cards.extend(get_content(html.text))
save_doc(cards,CSV)
pass
else:
print("Error")
parse()
这是我得到的一个错误:
Traceback (most recent call last):
File "C:\Users\win10\Desktop\path\PARSING\parsing.py", line 74, in <module>
parse()
File "C:\Users\win10\Desktop\path\PARSING\parsing.py", line 69, in parse
save_doc(cards,CSV)
File "C:\Users\win10\Desktop\path\PARSING\parsing.py", line 49, in save_doc
with codecs.open(path, 'w','utf-16',newline = '') as file:
TypeError: open() got an unexpected keyword argument 'newline'
起初,出现 Unicode 错误,CSV 文件无法正常显示俄罗斯字母。所以我在我的代码中添加了 utf-16 和“编解码器”模块,但现在我得到了这个错误。这是我正在尝试解析的网站https://minfin.com.ua/cards/
解决方案
在我的代码中添加了 utf-16 和“编解码器”模块,但现在我收到了这个错误。
open
本身确实接受encoding
作为参数,请尝试替换:
with codecs.open(path, 'w','utf-16',newline = '') as file
使用
with open(path, 'w', encoding='utf-16', newline='') as file
并检查运行此类更改代码的效果。
推荐阅读
- json - 如何以特定格式将 Excel 导出为 JSON
- java - 如何为多个java文件和资源创建一个可执行文件?
- wkwebview - WKWebView Swift - 获取 javascript 的 Console.log
- jenkins - Jenkins 工作目录在哪里?
- lua - 如何理解 lua 中的表?
- sql - 以增量方式以性能方式批量删除
- swift - 在具有两个相同 NSOutlineViews 的 macOS Cocoa 应用程序中,有没有办法在两者之间同步展开/折叠项目?
- java - Sping Cloud Stream Kafka - 以批处理模式消费消息并作为单个处理的消息发送
- html - 使用域名而不是本地网络中的本地 IP 地址时,无法访问 XAMPP 托管的本地 HTML 网站
- asp.net-mvc - 如何使用 ASP.NET MVC 将列表表视图链接到另一个表视图以获取详细信息