【发布时间】:2016-10-01 16:18:36
【问题描述】:
我在下面编写了这段代码,它按主题和日期从 OED.com 网站上抓取单词并将它们打印在一个列表中。
import requests
import re
import urllib2
import os
import csv
year_search = 1550
subject_search = ['Law']
path = '/Applications/Python 3.5/Economic'
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(opener)
user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
header = {'User-Agent':user_agent}
request = urllib2.Request('http://www.oed.com/', None, header)
f = opener.open(request)
data = f.read()
f.close()
print 'database first access was successful'
resultPath = os.path.join(path, 'OED_table.csv')
htmlPath = os.path.join(path, 'OED.html')
outputw = open(resultPath, 'w')
outputh = open(htmlPath, 'w')
request = urllib2.Request(
'http://www.oed.com/search?browseType=sortAlpha&case-insensitive=true'
'&dateFilter='+str(year_search)+'&nearDistance=1&ordered=false&page=1'
'&pageSize=100&scope=ENTRY&sort=entry&subjectClass='
+ str(subject_search) + '&type=dictionarysearch', None, header)
page = opener.open(request)
urlpage = page.read()
outputh.write(urlpage)
new_word = re.findall(
r'<span class=\"hwSect\"><span class=\"hw\">(.*?)</span>', urlpage)
print str(new_word)
outputw.write(str(new_word))
page.close()
outputw.close()
现在我想将它们打印到一个 CSV 文件中,但是我输入的每一年都将被放置为一行,并且所有单词都将落在该行的行中。
有点像:
1550| word1| word2| etc.|
1551| word1| word2| etc.|
有人有什么想法吗?
【问题讨论】:
-
我知道您将只有一年(在您的代码 1550 中),然后是一个单词列表(在您的代码
new_word中)。但我看不到你在哪里存储超过 1 年和一组单词。显示与某一年相对应的行就足够了吗? -
您的报废似乎不起作用。我尝试了几个不同的
year_search值,它们都返回了相同的东西,一个仅包含['nicker']的列表。请edit您的问题并将其更改为返回多个值的内容。
标签: python csv web-scraping