Python 3 网页抓取器非常简单,无法正常工作



我正在读一本《自学成才的程序员》一书,并且在使用一些 python 代码时遇到了麻烦。我让程序运行而没有任何错误。问题是没有任何输出。

import urllib.request
from bs4 import BeautifulSoup

class Scraper:
def __init__(self, site):
self.site = site
def scrape(self):
r = urllib.request
.urlopen(self.site)
html = r.read()
parser = "html.parser"
sp = BeautifulSoup(html, parser)
for tag in sp.find_all("a"):
url = tag.get("href")
if url is None:
continue
if "html" in url:
print("n" + url)
news = "https://news.google.com/"
Scraper(news).scrape()

看看最后一个"if"语句。如果 url 中没有文本"html",则不会打印任何内容。尝试删除它并取消缩进:

class Scraper:
def __init__(self, site):
self.site = site
def scrape(self):
r = urllib.request
.urlopen(self.site)
html = r.read()
parser = "html.parser"
sp = BeautifulSoup(html, parser)
for tag in sp.find_all("a"):
url = tag.get("href")
if url is None:
continue
print("n" + url)

最新更新