【问题标题】:HTTP Response automatically revised by read() of BeautifulSoupBeautifulSoup 的 read() 自动修改 HTTP Response
【发布时间】:2018-04-02 17:19:27
【问题描述】:

我正在尝试运行以下代码,但注意到bsObj1 的文本在我通过read() 提取其内容后被修改为空白文本。 bsObj3 也被修改为空白文本,而我没有做任何事情。

为什么bsObj1bsObj3 会变成空白?如何防止bsObj1被自动更改?

from urllib.request import urlopen
from bs4 import BeautifulSoup

def getLinks(pageUrl):
    html1 = urlopen(pageUrl)
    html2 = urlopen(pageUrl)
    html3 = html1

    body1 = html1.read()

    bsObj1 = BeautifulSoup(html1)
    bsObj2 = BeautifulSoup(html2)
    bsObj3 = BeautifulSoup(html3)

    print("bsObj1's length is "+str(len(bsObj1.text)))
    print("bsObj2's length is "+str(len(bsObj2.text)))
    print("bsObj3's length is "+str(len(bsObj3.text)))

if __name__ == '__main__':
    getLinks("https://en.wikipedia.org/wiki/Main_Page")

输出:-

bsObj1's length is 0
bsObj2's length is 16000
bsObj3's length is 0

提前非常感谢!

【问题讨论】:

    标签: python python-3.x web-scraping beautifulsoup urllib


    【解决方案1】:

    我相信您的代码中有错字。您已经阅读了 html1,因此当您将其解析为 BeautifulSoup 时,它不会读取任何内容,因为 body1 = html1.read()。已阅读 html1 已经与 html3 相同,因为它等于 html1

    所以下面的代码工作正常。

    body1 = html1.read()
    
    bsObj1 = BeautifulSoup(body1)
    bsObj2 = BeautifulSoup(html2)
    bsObj3 = BeautifulSoup(body1)
    

    样本输出

    bsObj1的长度是16028

    bsObj2的长度是16028

    bsObj3的长度是16028

    希望这会有所帮助。

    【讨论】:

    • 谢谢!这不是一个错字,但我不知道read() 会改变html1,因为我以为我只是在提取它的内容。对于html3,我尝试了html3.__repr__(),注意到它的内存地址与html1相同。有没有办法只复制对象而不共享相同的地址?
    • 如果您想了解有关复制对象的知识,您应该阅读以下内容:docs.python.org/2/library/copy.html
    猜你喜欢
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 2019-09-26
    • 2010-12-06
    相关资源
    最近更新 更多