命令行界面 (CLI)

下载并解析新闻文章。

usage: python -m newspaper [-h]
                           (--url URL | --urls-from-file URLS_FROM_FILE | --urls-from-stdin)
                           [--html-from-file HTML_FROM_FILE]
                           [--language LANGUAGE]
                           [--output-format {csv,json,text}]
                           [--output-file OUTPUT_FILE]
                           [--read-more-link READ_MORE_LINK]
                           [--skip-fetch-images] [--follow-meta-refresh]
                           [--browser-user-agent BROWSER_USER_AGENT]
                           [--proxy PROXY] [--request-timeout REQUEST_TIMEOUT]
                           [--cookies COOKIES] [--skip-ssl-verify]
                           [--max-nr-keywords MAX_NR_KEYWORDS] [--skip-nlp]

命名参数

--url, -u

要下载和解析的文章的URL。

--urls-from-file, -uf

包含待下载和解析文章URL的文件。

--urls-from-stdin, -us

从标准输入读取URL。

默认值:False

--html-from-file, -hf

要解析的HTML文件。这不会下载文章,而是直接解析HTML文件。

--language, -l

要下载和解析的文章的语言。

默认值: “en”

--output-format, -of

可能的选项:csv, json, text

解析文章的输出格式。

默认值:"json"

--output-file, -o

将解析后的文章写入的文件。

--read-more-link

用于获取全文链接的 xpath 选择器,适用于文章仅为摘要且需要点击"阅读更多"才能查看全文的情况。

--skip-fetch-images

在识别顶部图像时是否跳过获取图像。此选项可加快解析速度,但可能导致顶部图像识别错误。

默认:False

--follow-meta-refresh

在下载文章时是否跟随元刷新链接。

默认:否

--browser-user-agent, -ua

下载文章时使用的用户代理字符串。

--proxy

下载文章时使用的代理。格式为:http://: 例如:http://10.10.1.1:8080

--request-timeout

下载文章时使用的超时时间。

默认值: 7

--cookies

下载文章时使用的cookies。格式为:cookie1=value1; cookie2=value2; …

--skip-ssl-verify

是否跳过文章URL的证书验证

默认:False

--max-nr-keywords

从文章中提取关键词的最大数量。

默认值:10

--skip-nlp

是否跳过自然语言处理步骤。

默认值:False

示例

例如,您可以从CNN下载一篇文章并将其保存为JSON文件:

python -m newspaper --url=https://edition.cnn.com/2023/11/16/politics/ethics-committee-releases-santos-report/index.html  --output-format=json --output-file=cli_cnn_article.json

或者使用来自文本文件的URL列表(每行一个URL),并将所有结果存储为CSV:

python -m newspaper --urls-from-file=url_list.txt  --output-format=csv --output-file=articles.csv

你还可以使用管道重定向从标准输入读取URL:

grep "cnn" huge_url_list.txt | python -m newspaper --urls-from-stdin  --output-format=csv --output-file=articles.csv

要读取本地html文件的内容,请使用–html-from-file选项:

python -m newspaper --url=https://edition.cnn.com/2023/11/16/politics/ethics-committee-releases-santos-report/index.html --html-from-file=/home/user/myfile.html  --output-format=json

文件可以作为file://网址读取。如果您想保留原始网页网址,请使用带有–html-from-file的上一个示例:

python -m newspaper --url=file:///home/user/myfile.html  --output-format=json

将会打印出文章的json表示,针对存储在/home/user/myfile.html中的html文件。