前些年看到好多python爬虫技术于是自学了一波,今天把代码贴出来。
python版本 2.7,因为是自学所以可能有好多不足,反正贴出来跟大家交流一下,希望各位大佬多多提出意见。磕头了!
#函数1,根据关键字获取查询百度搜索结果(虽然百度的信息。。大家都懂,搜出来的都是给钱的)
def baidu_search(key_words,pagenum):
url='http://www.baidu.com/s?wd='+key_words+'&pn='+mymap[pagenum]
html=urllib2.urlopen(url).read()
return html
#函数2,处理一个要搜索的关键字,在文件夹目录下放个data.txt文件,把百度搜索结果放到data.txt中
def deal_key(key_words):
if os.path.exists('data')==False:
os.mkdir('data')
filename='data\\'+key_words.decode("utf-8")+'.txt'
fp=open(filename,'wb') #打开方式用‘w'时,下边的写要str转换,而对于网页要编码转换,遇到有些不规范的空格还出错
if fp:
pass
else:
print('文件打失败:'+filename)
return
x=0
while x<=7:
htmlpage=baidu_search(key_words,x)
soup=BeautifulSoup(htmlpage)
for item in soup.findAll("div", {"class": "result"}):
#*******这个格式应该参考百度网页布局*******
#一般我是右键-》检查 来定位元素
a_click = item.find('a')
if a_click:
fp.write(a_click.get("href").encode('utf-8'))
#链接
fp.write(b'#')
fp.write(b'\t\t\t\t\t\t')
if a_click:
fp.write(a_click.get_text().encode('utf-8'))
#标题
fp.write(b'#')
x=x+1
fp.write(b'\n')
fp.close()
#函数3,读取搜索文件内容,依次取出要搜索的关键字
def search_file():
fp=open('searchfile.txt')
i=0
keyword=fp.readline()
while keyword:
i=i+1
if i==5:
print('sleep...')
time.sleep(6)
print('end...')
i=0
nPos=keyword.find('\n')
if nPos>-1:
keyword=keyword[:-1]#keyword.replace('\n','')
deal_key(keyword)
keyword=fp.readline()
#脚本入口
print('Start:')
search_file()
print('End!')