【发布时间】:2016-07-02 20:42:18
【问题描述】:
from bs4 import BeautifulSoup
import requests
import os
url = "http://nos.nl/artikel/2093082-steeds-meer-nekklachten-bij-kinderen-door-gebruik-tablets.html"
r = requests.get(url)
soup = BeautifulSoup(r.content.decode('utf-8', 'ignore'))
data = soup.find_all("article", {"class": "article"})
with open("data1.txt", "wb") as file:
content=‘utf-8’
for item in data:
content+='''{}\n{}\n\n{}\n{}'''.format( item.contents[0].find_all("time", {"datetime": "2016-03-16T09:50:30+0100"})[0].text,
item.contents[0].find_all("a", {"class": "link-grey"})[0].text,
item.contents[0].find_all("img", {"class": "media-full"})[0],
item.contents[1].find_all("div", {"class": "article_textwrap"})[0].text,
)
with open("data1.txt".format(file_name), "wb") as file:
file.write(content)
最近解决了一个 utf/Unicode 问题,但现在它没有将其保存为 .txt 文件,也根本没有保存它。我需要做什么?
【问题讨论】:
-
A:您正在打开文件以写入字节,然后尝试向其写入字符串,B:
"data1.txt".format(file_name)对file_name的作用并不大,而且它没有定义所以我真的很困惑你想要做什么...... -
你认为
"data1.txt".format(file_name)在做什么?还有你为什么要以wb模式打开? -
我正在尝试将所有 item.contents 中的内容保存到 .txt 文件中。 (stackoverflow.com/questions/36039919/…)
标签: python save beautifulsoup