python - BeautifulSoup 无法获取页面的所有源代码,只有几行
问题描述
from urllib.request import urlopen
from bs4 import BeautifulSoup
page_origin = urlopen("https://stackoverflow.com")
page_html = page_origin.read()
page_origin.close()
print(page_html)
结果是https://stackoverflow.com的完整 html 代码。它工作正常。因为太长,就不贴了。
问题在于 BeautifulSoup。我添加了两行代码来使用 BeautifulSoup 来分析 html。奇怪的事情发生了。它根本没有用。
from urllib.request import urlopen
from bs4 import BeautifulSoup
page_origin = urlopen("https://stackoverflow.com")
page_html = page_origin.read()
page_origin.close()
# print(page_html)
page_soup = BeautifulSoup(page_html, features="lxml", from_encoding="gbk")
print(page_soup)
结果非常非常简单。
<!DOCTYPE html>
<html class="html__responsive">
<head>
<title>
Stack Overflow - Where Developers Learn, Share, & Build Careers
</title>
<link href="https://cdn.sstatic.net/Sites/stackoverflow/img/favicon.ico?v=4f32ecc8f43d" rel="shortcut icon"/>
<link href="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png?v=c78bd457575a" rel="apple-touch-icon image_src"/>
<link href="/opensearch.xml" rel="search" title="Stack Overflow" type="application/opensearchdescription+xml"/>
</head>
</html>
这不是html的完整代码,我根本无法分析。
请帮助我,我调试了太多时间。谢谢。
解决方案
这为我提供了完整的源代码:
import requests
from bs4 import BeautifulSoup
r = requests.get('https://stackoverflow.com/')
soup = BeautifulSoup(r.text, 'lxml')
print(soup)
推荐阅读
- ms-access - Visual Studio 将 VB 项目连接到 .accde 数据库
- tortoisegit - 如何使用 TortoiseGit 从远程 git 存储库中获取笔记?
- c# - 无效的密钥哈希。我通过facebook登录游戏时出错
- javascript - Vue.js @click 只注册了一半的时间
- python - 尝试将 tkinter 中的图像正确显示到类的方法中
- go - go rpc 内存泄漏还是不了解?
- ruby - 更新 Ruby Mac OS 10.6.8 Snow Leopard
- javascript - (Javascript) 需要帮助将对象转换为数组
- amazon-web-services - Kinesis 到 S3 自定义分区
- r - 在列表中包含列表