我有一个流行文章的网页,我想抓取每个引用网页的超链接及其所显示文章的标题。
我的脚本所需的输出是一个 CSV 文件,其中在一行中列出了每个标题和文章内容。因此,如果该网页上有 50 篇文章,我想要一个包含 50 行和 100 个数据点的文件。
我的问题是文章标题及其超链接包含在 SVG 容器中,这让我感到困惑。我以前曾使用 BeautifulSoup 进行网页抓取,但不知道如何选择每篇文章的标题和超链接。非常感谢任何和所有的帮助。
import requests
from bs4 import BeautifulSoup
import re
res = requests.get('http://fundersandfounders.com/what-internet-thinks-based-on-media/')
res.raise_for_status()
playFile = open('top_articles.html', 'wb')
for chunk in res.iter_content(100000):
playFile.write(chunk)
f = open('top_articles.html')
soup = BeautifulSoup(f, 'html.parser')
links = soup.select('p') #i know this is where i'm messing up, but i'm not sure which selector to actually utilize so I'm using the paragraph selector as a place-holder
print(links)
我知道这实际上是一个两步项目:我的脚本的当前版本不会迭代我要抓取其实际内容的所有超链接的列表。这是我自己可以轻松执行的第二步,但是如果有人也想写这一点,请向您致敬。
您应该分两步进行:
- 解析 HTML 并提取指向的链接
svg
- 下载
svg
页面,解析它BeautifulSoup
并提取“气泡”
执行:
from urllib.parse import urljoin # Python3
import requests
from bs4 import BeautifulSoup
base_url = 'http://fundersandfounders.com/what-internet-thinks-based-on-media/'
with requests.Session() as session:
# extract the link to svg
res = session.get(base_url)
soup = BeautifulSoup(res.content, 'html.parser')
svg = soup.select_one("object.svg-content")
svg_link = urljoin(base_url, svg["data"])
# download and parse svg
res = session.get(svg_link)
soup = BeautifulSoup(res.content, 'html.parser')
for article in soup.select("#bubbles .bgroup"):
title, resource = [item.get_text(strip=True, separator=" ") for item in article.select("a text")]
print("Title: '%s'; Resource: '%s'." % (title, resource))
打印文章标题和资源:
Title: 'CNET'; Resource: 'Android Apps That Extend Battery Life'.
Title: '5-Years-Old Shoots Sister'; Resource: 'CNN'.
Title: 'Samsung Galaxy Note II'; Resource: 'Engaget'.
...
Title: 'Predicting If a Couple Stays Together'; Resource: 'The Atlantic Magazine'.
Title: 'Why Doctors Die Differently'; Resource: 'The Wall Street Journal'.
Title: 'The Ideal Nap Length'; Resource: 'Lifehacker'.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)