词语相似度计算:3、使用urllib爬取wiki文章,使用beautifulSoup解析html

本文介绍了一种使用Python爬取维基百科词条的方法。通过urllib2和BeautifulSoup库,实现了自动请求指定词条页面并解析提取前三段落文本的功能。此爬虫适用于批量抓取词条简介。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

详细介绍参考:

http://blog.youkuaiyun.com/mmc2015/article/details/50923309


完整代码供大家参考。。。。

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #!usr/bin/env  
  2. # -*-coding:utf-8 -*-  
  3.   
  4.   
  5.   
  6. import pandas as pd  
  7. import numpy as np  
  8.   
  9. import urllib, urllib2  
  10. import re  
  11. from bs4 import BeautifulSoup  
  12.   
  13.   
  14. import sys  
  15. reload(sys)  
  16. sys.setdefaultencoding("utf8")  
  17. #for UnicodeEncodeError  
  18.   
  19.   
  20.   
  21. def SaveFile(content, filename):  
  22.     f=open("wikiData/"+filename,"a")  
  23.     f.write(str(content)+"\n")  
  24.     f.close()  
  25.   
  26.   
  27. def SpideWiki(words):  
  28.     user_agent='Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'  
  29.     headers={'User-Agent':user_agent}  
  30.     try:  
  31.         for i in range(len(words)):  
  32.             url="https://en.wikipedia.org/wiki/"+words[i]  
  33.             request=urllib2.Request(url, headers=headers)  
  34.             response=urllib2.urlopen(request)  
  35.             wikiHtml=response.read().decode('utf-8')  
  36.             html=BeautifulSoup(str(wikiHtml),"lxml")  
  37.             div=html.find(name='div', id='mw-content-text')  
  38.             ps=div.find_all(name='p', limit=3, recursive=False#only direct children  
  39.             for p in ps:  
  40.                 pText=p.get_text()  
  41.                 SaveFile(pText, words[i])  
  42.             print words[i], "process over...""=="*20  
  43.     except urllib2.URLError, e:  
  44.         if hasattr(e,"code"):  
  45.             print e.code  
  46.         if hasattr(e,"reason"):  
  47.             print e.reason  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值