如何使用urllib2读取页面源代码?

2024-05-23 22:13:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图阅读由内容管理系统(CMS)托管的网页的页面源代码

要通过浏览器查看网页,我输入URL,输入用户名和密码(通过域(intranet)验证)。当我右键单击网页时>;查看源代码,我得到标签中的所有页面内容。该页面包含许多h1、h2、p和table标记

我想运行一个脚本来获取页面源代码。当我执行下面的代码时,我没有得到完整的页面源代码(在标记中)

import urllib
import urllib2
import webbrowser

testlink = 'mylinkwithinCMS'

auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',uri='mydomain', user='myusername', passwd='mypassword')
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
response = urllib2.urlopen(testlink)

with open('output.txt', 'w') as f:
    f.write(response.read())

我只得到一行代码,如下所示:

<body><script type="text/javascript">window.NREUM||(NREUM={});NREUM.info={"beacon":"bam.nr-data.net","licenseKey":"0f4bf752fg”,”applicationID":"135707588”,”transactionName":"ZwZaYBQFXktSVhBZDl5MbUYPS1NXQVBAgFIFkNdFA==","queueTime":0,"applicationTime":270,"atts":"S0FZFlwfTUU=","errorBeacon":"bam.nr-data.net","agent":""}</script></body>

Tags: 代码标记importauth网页内容源代码response