Python 网络抓取:抓取后无法写入文件

Python web scraping: failed to write to file after scraping

我正在自己练习网页抓取,并试图从一个中文在线小说网站上抓取 python 的网络小说系列。在我将 python 代码放入一个函数后,它似乎停止运行了。 我写了一段这样的代码:


import requests
from bs4 import BeautifulSoup


page = requests.get('https://www.51shucheng.net/zh-tw/wuxia/shediaoyingxiongzhuan')
soup = BeautifulSoup(page.content,'lxml')

page_list = soup.find_all(class_='mulu-list')
pages = page_list[0].find_all('a')
print(pages[0])

for i in range(len(pages)):
    pages[i] = pages[i].get('href')
    

with open("射雕英雄傳1.txt", "w+") as file_object:
    for i in range(len(pages)):
        file_object.write('\n\n\t{}'.format(i+1))
        page = requests.get(pages[i])
        soup = BeautifulSoup(page.content,'lxml')
        content = soup.find(class_='neirong').text
        print(content[0:20])
        file_object.write(content)


with open('射雕英雄傳1.txt') as oldfile, open('射雕英雄傳.txt', 'w') as newfile:
    for line in oldfile:
        if not ('adsbygoogle' in line):
            newfile.write(line)    

而且效果很好。但是,我想将它包含在一个函数中,因此我做了以下修改。然后它就失败了:'射雕英雄传1.txt'文件仍然创建,但它是空的。


import requests
from bs4 import BeautifulSoup


def scraping_novel(prefix,bookname):
    page = requests.get('https://www.51shucheng.net/zh-tw/wuxia/{}'.format(prefix))
    soup = BeautifulSoup(page.content,'lxml')
    
    page_list = soup.find_all(class_='mulu-list')
    pages = page_list[0].find_all('a')
    print(pages[0])
    for i in range(len(pages)):
        pages[i] = pages[i].get('href')
        
    with open("{}1.txt".format(bookname), "w+") as file_object:
        for i in range(len(pages)):
            file_object.write('\n\n\t{}'.format(i+1))
            page = requests.get(pages[i])
            soup = BeautifulSoup(page.content,'lxml')
            content = soup.find(class_='neirong').text
            print(content[0:20])
            file_object.write(content)

    with open("{}1.txt".format(bookname)) as oldfile, open("{}1.txt".format(bookname), 'w') as newfile:
        for line in oldfile:
            if not ('adsbygoogle' in line):
                newfile.write(line)    


scraping_novel("shediaoyingxiongzhuan","射雕英雄傳")                


#failed

我试过两件事:

  1. 将文件名从中文改成英文,我认为可能是编码问题,但无济于事。事实上,这不是我第一次抓取非英文网站,而且我从未见过这样的东西。
  2. 在第一个 With 语句中,倒数第二行 print(content[0:20]),我试图检查内容。完全没问题,所以我认为问题不在于 BS,而在于文件写入。输出文件中没有任何内容!顺便说一句,输出文件大小为零字节。

如果有人能告诉我发生了什么,我将不胜感激,因为我仍然无法弄清楚哪里出了问题。

使用 python >= 3.6? 做

open(f"{bookname}.txt", 'w') as newfile

但是对于文件的覆盖。我猜你不能那样做。您在一条语句中打开同一个文件进行读写。

with open("1.txt", "w+") as oldfile:
    oldfile.write('test')

differentName = "12.txt"
with open("1.txt", "r") as oldfile, open(differentName, 'w') as newfile:
    assert(len(oldfile.readlines()))     

sameName = "1.txt"
with open(sameName, "r") as oldfile, open(sameName, 'w') as newfile:
    assert(len(oldfile.readlines()))

@Lydia van Dyke 提到的错字导致文件被打开用于写入并提前结束读取流。所以 oldfile 行上的循环执行了 0 次。