网页文章自动采集(Excel教程Excel函数Excel透视表Excel电子表格Excel基础入门到精通Excel实用技巧Excel2010高效办公office2010Excel视频教程 )

优采云 发布时间: 2021-10-08 23:25

  网页文章自动采集(Excel教程Excel函数Excel透视表Excel电子表格Excel基础入门到精通Excel实用技巧Excel2010高效办公office2010Excel视频教程

)

  要求:通过程序下载网页,用不同的方法导出所有的链接采集 [注意:只能带href,href的值不能以#开头,不能收录JavaScript/vbscript。 ].

  1、使用字符串处理方式导出所有链接采集,格式为名称及其对应的链接,注意:不能依赖BS4;

  2、使用正则表达式,把采集的所有链接都放出来,格式为名称及其对应的链接,注意:不能依赖BS4;

  3、使用BS方式采集out所有链接,格式为名称及其对应的链接;

  链接:点击打开链接

  代码 1:

  import requests

### 获取网页内容

url = 'http://www.pku.edu.cn'#定义url

res = requests.get(url)

res.encoding = "utf-8" # 设置网页编码

###将网页内容整合为一行

strTxt=res.text.replace('\n','')

### 开始处理字符串 ##############

#分割字符串

allFind=strTxt.split(r"</a>")

#用字典来保存链接

dictA={}

#对每一个含有链接的str做处理

for include_a in allFind:

#寻找链接的开始位置

if(&#39;&#39; in tem ):

#print(tem)

#这样一分割,nameList[1]就是名称

nameList = tem.split(&#39;>&#39;)

name=nameList[1]

#print(name[1])

##再次分割,href的后“之前的就是需要的东西

index_href=nameList[0].index(&#39;href&#39;)

##+6直接去掉 href="

hrefList=nameList[0][index_href+6:].split("\"")

#href就是 hrefList[0]

href=hrefList[0]

#print(href[0])

#做一些判断 按照要求,href开头不能为#,href中不能含有javascript/vbscript,有一些图片,直接删除

if (href != &#39;&#39;) and (href[0]!= &#39;#&#39;) and (&#39;javascript&#39; not in href) and (

&#39;vbscript&#39; not in href) and &#39;img&#39;not in name and name!="":

#做一些优化,如果连接不完整,则补上前缀

if href[0:4]!=&#39;http&#39;:

href=&#39;http://www.pku.edu.cn/&#39;+href

dictA[name]=href

#print(&#39;------------------------------&#39;)

####### 输出保存 ##########################################################

numA=0

for i in dictA:

print(i,dictA[i],sep=" ")

numA+=1

print(numA)

fd=open(&#39;./txt/1.txt&#39;,&#39;w&#39;,encoding=&#39;utf-8&#39;)

for i in dictA:

print(i,dictA[i],file=fd,sep="\t")

fd.close()

  代码 2:

<p>import requests

import re

#### 获取网页内容 ############################

url = &#39;http://www.pku.edu.cn&#39;#定义url

res = requests.get(url)

res.encoding = "utf-8" # 设置网页编码

###将网页内容整合为一行

strTxt=res.text.replace(&#39;\n&#39;,&#39;&#39;)

### 开始处理字符串 ########################

#找到所有的链接

allFind=re.findall(r"

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线