用python抓取一个网站,需要解决以下问题:
beautiful soup 文档:
http://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html
 
1,用python模拟useragent为android的浏览器:
 
复制代码 代码示例:
useragent = "Mozilla/5.0 (
linux; U; Android 2.2; en-gb; GT-P1000 Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"  
url = "http://xxx"  
request = urllib2.Request(url)  
request.add_header('User-Agent',useragent)  
html = urllib2.urlopen(request,timeout=5).read()  
  
#
url编码  
urllib.quote(‘abc edf')  
 
2,beautiful soup 用的最多的一些方法
 
复制代码 代码示例:
soup = BeautifulSoup(html)  
print soup.strong.string  
print soup.find("div",class_='xxx').string  
print soup.find("span",class_='pos').next_sibling.string  
oneDiv.next_sibling.a.get("href")  
# 获取一个div,并且class='xxx' 的一个div,.string 为获取这个div里的文本。
.next_sibling 下一个同级节点。
3,正则提取文本中以http开头和以html结尾的文本:
 
复制代码 代码示例:
p=re.compile(r"""(http://.*.html)""").search(oneString)  
if p:  
   return p.group(1) 
4,下载文件
 
复制代码 代码示例:
urllib.urlretrieve("http://xxx/asd.jpg",'apple.jpg') 
抓取就可以开始了,然后对应上出现的一场来解决问题就行。