python爬取百度标题_Python实现抓取百度搜索结果页的网站标题信息

__author__ = '曾是土木人'

# -*- coding: utf-8 -*-

#采集SERP搜索结果标题

import urllib2

from bs4 import BeautifulSoup

import time

#写文件

def WriteFile(fileName,content):

try:

fp = file(fileName,"a+")

fp.write(content + "\r")

fp.close()

except:

pass

#获取Html源码

def GetHtml(url):

try:

req = urllib2.Request(url)

response= urllib2.urlopen(req,None,3)#设置超时时间

data = response.read().decode('utf-8','ignore')

except:pass

return data

#提取搜索结果SERP的标题

def FetchTitle(html):

try:

soup = BeautifulSoup(''.join(html))

for i in soup.findAll("h3"):

title = i.text.encode("utf-8")

if any(str_ in title for str_ in ("北京","厦门")):

continue

else:

print title

WriteFile("Result.txt",title)

except:

pass

keyword = "58同城"

if __name__ == "__main__":

global keyword

start = time.time()

for i in range(0,8):

url = "http://www.baidu.com/s?wd=intitle:"+keyword+"&rn=100&pn="+str(i*100)

html = GetHtml(url)

FetchTitle(html)

time.sleep(1)

c = time.time() - start

print('程序运行耗时:%0.2f 秒'%(c))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这里是一个简单的Python-Scrapy爬取百度搜索结果并对搜索结果进行分析的例子: 首先,我们需要安装Scrapy和lxml库。在命令行中输入以下命令: ``` pip install scrapy pip install lxml ``` 然后,我们可以创建一个名为baidu_spider的新项目,并在项目中创建一个名为baidu的新爬虫。在命令行中输入以下命令: ``` scrapy startproject baidu_spider cd baidu_spider scrapy genspider baidu www.baidu.com ``` 现在,我们在baidu_spider/spiders/baidu.py文件中编写我们的代码。我们将使用Scrapy的Selector来选择我们想要的数据。代码如下: ```python import scrapy class BaiduSpider(scrapy.Spider): name = "baidu" allowed_domains = ["www.baidu.com"] start_urls = ["http://www.baidu.com/s?wd=python"] def parse(self, response): # 获取搜索结果 results = response.xpath('//div[@class="result c-container "]') for result in results: # 获取标题和链接 title = result.xpath('.//h3/a/text()').extract_first().strip() link = result.xpath('.//h3/a/@href').extract_first() # 获取摘要 abstract = result.xpath('.//div[@class="c-abstract"]//text()').extract() abstract = "".join(abstract).strip() # 打印结果 print(title) print(link) print(abstract) ``` 在这个例子中,我们首先定义了我们的爬虫的名称,允许的域名和起始URL。然后我们定义了一个parse函数来处理响应。在parse函数中,我们使用XPath选择器来选择搜索结果。我们使用extract_first()和extract()方法来提取标题、链接和摘要。最后,我们打印了结果。 现在,我们可以在baidu_spider目录中运行以下命令来运行我们的爬虫: ``` scrapy crawl baidu ``` 这将启动我们的爬虫并开始爬取百度搜索结果。在控制台中,您应该能够看到我们的爬虫正在输出搜索结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值