python-3.x - 从新闻文章中抓取网页
问题描述
我一直在尝试访问给定新闻网站的链接。我发现代码运行良好,但唯一的问题是,它输出“javascript:void();” 以及所有其他链接。请让我知道我可以进行哪些更改以使我不会遇到“javascript:void();” 在所有其他链接的输出中。以下是代码:
from bs4 import BeautifulSoup
from bs4.dammit import EncodingDetector
import requests
parser = 'html.parser' # or 'lxml' (preferred) or 'html5lib', if installed
resp = requests.get("https://www.ndtv.com/coronavirus?pfrom=home-mainnavgation")
http_encoding = resp.encoding if 'charset' in resp.headers.get('content-type', '').lower() else None
html_encoding = EncodingDetector.find_declared_encoding(resp.content, is_html=True)
encoding = html_encoding or http_encoding
soup = BeautifulSoup(resp.content, parser, from_encoding=encoding)
for link in soup.find_all('a', href=True):
print(link['href'])
解决方案
如果您不想要它们,只需将它们过滤掉即可。
就是这样:
import requests
from bs4 import BeautifulSoup
from bs4.dammit import EncodingDetector
resp = requests.get("https://www.ndtv.com/coronavirus?pfrom=home-mainnavgation")
http_encoding = resp.encoding if 'charset' in resp.headers.get('content-type', '').lower() else None
html_encoding = EncodingDetector.find_declared_encoding(resp.content, is_html=True)
encoding = html_encoding or http_encoding
soup = BeautifulSoup(resp.content, 'html.parser', from_encoding=encoding)
for link in soup.find_all('a', href=True):
if link["href"] != "javascript:void();":
print(link['href'])
推荐阅读
- python - Python 数据转换 If df[column] = "A" then df[column] = 1 - (将 "A" 替换为 1)
- android-studio - 模拟器:警告:setGeometry:无法设置几何
- r - 在 R 中调用 names() 时不要打印任何内容
- c# - 单击卡片的提交按钮后如何恢复瀑布聊天机器人?
- java - openjdk 9 的 InvalidAlgorithmParameterException
- java - 将数组作为参数传递给类
- php - 在 codeigniter 中为订阅计划自动定期付款
- r - 在定义 S3 方法时,我应该显式导入泛型方法吗?
- scala - 像 first()、head()、isEmpty().. 这样的 RDD 操作,它们是否评估整个 RDD?还是只是其中的一部分?
- python - VSCode中的Python即使更改为正确的环境也找不到模块