我正在尝试将数据导出为.txt文件
from bs4 import BeautifulSoup
import requests
import os
import os
os.getcwd()
'/home/folder'
os.mkdir("Probeersel6")
os.chdir("Probeersel6")
os.getcwd()
'/home/Desktop/folder'
os.mkdir("img") #now `folder`
url = "http://nos.nl/artikel/2093082-steeds-meer-nekklachten-bij-kinderen-door-gebruik-tablets.html"
r = requests.get(url)
soup = BeautifulSoup(r.content)
data = soup.find_all("article", {"class": "article"})
with open(""%s".txt", "wb" %(url)) as file:
for item in data:
print item.contents[0].find_all("time", {"datetime": "2016-03-16T09:50:30+0100"})[0].text
print item.contents[0].find_all("a", {"class": "link-grey"})[0].text
print "\n"
print item.contents[0].find_all("img", {"class": "media-full"})[0]
print "\n"
print item.contents[1].find_all("div", {"class": "article_textwrap"})[0].text
file.write()
应该放在:
file.write()
上班?
我还试图将.txt文件的名称与url相同,应该使用字符串吗?
with open(""%s".txt", "wb" %(url)) as file:
url = "http://nos.nl/artikel/2093082-steeds-meer-nekklachten-bij-kinderen-door-gebruik-tablets.html"
解决方法:
您应该将Inside file.write您的内容.我可能会做类似的事情:
#!/usr/bin/python3
#
from bs4 import BeautifulSoup
import requests
url = 'http://nos.nl/artikel/2093082-steeds-meer-nekklachten-bij-kinderen-door-gebruik-tablets.html'
file_name=url.rsplit('/',1)[1].rsplit('.')[0]
r = requests.get(url)
soup = BeautifulSoup(r.content, 'lxml')
data = soup.find_all('article', {'class': 'article'})
content=''.join('''{}\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,
) for item in data)
with open('./{}.txt'.format(file_name), mode='wt', encoding='utf-8') as file:
file.write(content)