c爬虫抓取网页数据(写入值到word二、spider爬取标题进行写入三、爬去代码并将代码进行装换遇到问题 )

优采云 发布时间: 2022-02-24 14:09

  c爬虫抓取网页数据(写入值到word二、spider爬取标题进行写入三、爬去代码并将代码进行装换遇到问题

)

  一、将值写入word 二、蜘蛛爬取标题供写三、爬取代码并替换代码遇到的问题:

  

  在代码块中,每个字符都用一个 span 包裹

  

  这种方法可以直接获取代码的值,可以用它来获取代码思路一、直接模仿代码进行在线替换,编写操作思路二、使用文件操作技术获取替换的代码,然后使用脚本将其复制并粘贴到word文档中。 Ideas三、通过拼接直接得到的span标签的值,将拼接后的值传入word(select)中,最后使用etree执行代码块。解析项目遇到的工具:

  

  

  (etree)

  (查询)

  代码:

  import requests

from bs4 import BeautifulSoup

from pyquery import PyQuery as pq

from lxml import etree

from docx import Document

from docx.shared import Inches

url="https://www.runoob.com/cprogramming/c-exercise-example"

def geu_page(url):

try:

res = requests.get(url,timeout=4)

res.encoding = 'utf-8'

if res.status_code == 200:

html = res.text

return html.encode("utf-8")

except Exception as e:

for i in range(3):

print(url,e)

res = requests.get(url,timeout=4)

res.encoding = 'utf-8'

if res.status_code == 200:

html = res.text

return html.encode('utf-8')

def getdata(url1):

html1 = geu_page(url1)

doc = pq(html1) # 解析html文件

datas = etree.HTML(html1)

data = datas.xpath('//div[@class="hl-main"]/span/text()')

code = ''.join(data)

title = doc('#content > p:nth-child(3)').text() # 其中doc(使用的是selector选择器)

content = doc('#content > p:nth-child(4)').text()

# 对url进行切割获取下标

begin = url1.find("example")

end = url1.find(".html")

index = url1[begin + 7:end]

print("开始写入第"+index+"个实例")

write_to_word(code,title,content,head=index)

def write_to_word(code,title,content,head):

# 标题

document.add_heading("C语言实例"+str(head), level=0)

# 文本: 题目

document.add_paragraph(title)

# 文本: 程序分析

document.add_paragraph(content)

# 代码: 代码

document.add_paragraph(code)

# 结果: result

document = Document()

for i in range(1,101):

url1=url+str(i)+".html"

getdata(url1)

document.save('C 语言经典100例.docx')

ent()

for i in range(1,101):

url1=url+str(i)+".html"

getdata(url1)

document.save('C 语言经典100例.docx')

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线