import requests from bs4 import BeautifulSoup url = 'https://b.guidaye.com/changxiao/9948/' def getCpontent(url): response = requests.get(url).content.decode('gbk',errors='ignore') soup = BeautifulSoup(response,'html.parser') content = soup.find('div',class_='mb2').text return content def getTitleLink(url): html = requests.get(url).content.decode('utf-8') soup = BeautifulSoup(html,'html.parser') chapters = soup.find('div',class_='book-list mb clearfix') chapters = chapters.find_all('a') titleLink = {} for each in chapters: title = each.text link = ('https://b.guidaye.com/'+each.get('href')) titleLink[title] = link return (titleLink) def main(): titleLink = getTitleLink(url) for title,link in titleLink.items(): f = open('天才在左疯子在右.txt','a') print(title) f.write(title) f.write(getCpontent(link)) f.close() main() 哪里出问题了
时间: 2024-04-02 17:34:56 浏览: 122
代码中出现了一个语法错误,即在第一行的导入语句中,应该使用import关键字,而不是从关键字。正确的代码应该是:
```
import requests
from bs4 import BeautifulSoup
url = 'https://b.guidaye.com/changxiao/9948/'
def getContent(url):
response = requests.get(url).content.decode('gbk',errors='ignore')
soup = BeautifulSoup(response,'html.parser')
content = soup.find('div',class_='mb2').text
return content
def getTitleLink(url):
html = requests.get(url).content.decode('utf-8')
soup = BeautifulSoup(html,'html.parser')
chapters = soup.find('div',class_='book-list mb clearfix')
chapters = chapters.find_all('a')
titleLink = {}
for each in chapters:
title = each.text
link = ('https://b.guidaye.com/'+each.get('href'))
titleLink[title] = link
return (titleLink)
def main():
titleLink = getTitleLink(url)
for title,link in titleLink.items():
f = open('天才在左疯子在右.txt','a')
print(title)
f.write(title)
f.write(getContent(link))
f.close()
if __name__ == '__main__':
main()
```
此外,还需要注意在main函数的最后加上if __name__ == '__main__':,以便在其他模块调用该函数时,不会执行main函数。
阅读全文