|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import requests
from bs4 import BeautifulSoup
import re
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'
}
def getChengyu(cate, page):
f=open("chengyu_urls.csv","a",encoding="utf-8")
res=requests.get("https://www.chengyucidian.net/letter/"+str(cate)+"/p/"+str(page), headers=headers, allow_redirects=False)
res.encoding="utf-8"
soup=BeautifulSoup(res.text)
urls=soup.select('div[class="cate"]')
print(urls)
urls=re.findall('\d+',str(urls))
for url in urls:
f.write("https://www.chengyucidian.net/cy/"+str(url)+".html"+"\n")
def getPageNum(cate):
res = requests.get("https://www.chengyucidian.net/letter/"+str(cate), headers=headers, allow_redirects=False)
res.encoding="utf-8"
soup=BeautifulSoup(res.text)
pagenum=soup.select('div[class="page"]')
pagenum=re.findall('\d+',str(pagenum))[-1]
return pagenum
def getIntroduction(url):
res = requests.get(url, headers=headers, allow_redirects=False)
res.encoding = "utf-8"
soup = BeautifulSoup(res.text)
chengyu=soup.select('h1')
chengyu=str(chengyu[0]).replace("<h1>","")
chengyu=chengyu.replace("</h1>","")
print(chengyu)
introText = soup.select('div[class="con"]')
introText=str(introText[0]).replace("<p>","")
introText = introText.replace("</p>", "")
introText = introText.replace('<h4 id="chu">', "")
introText = introText.replace('<h4 id="shi">', "")
introText = introText.replace('</h4>', "")
introText = introText.replace('<h4>', "")
introText = introText.replace('<div class="con">', "")
introText = introText.replace('</div>', "")
introText = introText.replace('<strong>', "")
introText = introText.replace('</strong>', "")
introText = introText.replace('<p class="ciLs">', "")
print(introText)
return chengyu, introText
if __name__=="__main__":
f1=open("chengyu_urls.csv","r",encoding="utf-8")
f2=open("chengyu_introText.csv","a",encoding="utf-8")
urls=f1.read().split("\n")
print(len(urls))
for url in urls[10:]:
chengyu,introText=getIntroduction(url)
f2.write(str(chengyu)+"\n"+"["+str(introText)+"]"+"\n")
返回值:
>>>
===================== RESTART: C:\Users\wepie\Desktop\11.py ====================
2
>>>
|
|