我怎样才能使这个代码工作?,我使用 beautifulsoup4 并且我无法将该值抓取到

抱歉,我对编码不熟悉,但我真的很想学习。我无法传递我想要的值,在这种情况下,这只是我想从网络上抓取的数字。


问题是我无法将我用 beautifulsoup 抓取的值传递到 csv 文件,任何好心人可以帮助我吗?


from bs4 import BeautifulSoup

from urllib.request import Request, urlopen

import csv




req = Request('https://www.infodolar.com.mx/tipo-de-cambio-dof-diario-oficial-de-la-federacion.aspx', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'})

html_page = urlopen(req).read()


soup = BeautifulSoup(html_page,'html.parser')


Dollar = soup.find('td','colCompraVenta')


print (Dollar.text)


file=open('New.csv', 'wb')

writer = csv.writer(file)






writer.writerows([Dollar.encode('utf-8')])


file.close()


尚方宝剑之说
浏览 82回答 1
1回答

宝慕林4294392

将此行更改为file=open('New.csv', 'wb')您file=open('New.csv', 'w') 的代码将如下所示from bs4 import BeautifulSoupfrom urllib.request import Request, urlopenimport csvreq = Request('https://www.infodolar.com.mx/tipo-de-cambio-dof-diario-oficial-de-la-federacion.aspx', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'})html_page = urlopen(req).read()soup = BeautifulSoup(html_page,'html.parser')Dollar = soup.find('td','colCompraVenta')print (Dollar.text)file=open('New.csv', 'w')writer = csv.writer(file)writer.writerows([Dollar.encode('utf-8')])file.close()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python