Python 编写脚本来抓取站点并以JSON格式输出其数据?
我被一个问题困住了。我想获取这个站点所有公司列表数据的JSON 每个链接端点都保存公司特定的数据,如公司名称、描述、邮政编码、州和地址 我最初的想法是: 将站点列表放入列表中 可能会使用请求。可能会再次获取每个端点 到目前为止,我已经尝试了几种方法,以下是我的最新尝试:Python 编写脚本来抓取站点并以JSON格式输出其数据?,python,json,python-2.7,beautifulsoup,bs4,Python,Json,Python 2.7,Beautifulsoup,Bs4,我被一个问题困住了。我想获取这个站点所有公司列表数据的JSON 每个链接端点都保存公司特定的数据,如公司名称、描述、邮政编码、州和地址 我最初的想法是: 将站点列表放入列表中 可能会使用请求。可能会再次获取每个端点 到目前为止,我已经尝试了几种方法,以下是我的最新尝试: import requests from bs4 import BeautifulSoup base_url = "http://data-interview.enigmalabs.org/companies/" r =
import requests
from bs4 import BeautifulSoup
base_url = "http://data-interview.enigmalabs.org/companies/"
r = requests.get(base_url)
soup = BeautifulSoup(r.content, 'html.parser')
links = soup.find_all("a")
link_list = []
for link in links:
print link_list.append("<a href='%s'</a>" %(link.get("href")))
我不知道如何从各个页面提取我需要的所有数据,你的问题具体是什么?这似乎相当宽泛。@Carcigenicate我不知道如何从各个页面提取我需要的所有数据,然后存储在JSONWow中!我真的很喜欢你的解决方案。比我最初想象的要简单得多。再次感谢您,我也完全理解了您的方法。
import bs4, urlparse, json, requests
from os.path import basename as bn
links = [] # the relative paths to companies
data = {} # company name --> company data
base = 'http://data-interview.enigmalabs.org/'
def bs(r): # returns a beautifulsoup table object for the table in the page of the relative path
return bs4.BeautifulSoup(requests.get(urlparse.urljoin(base, r).encode()).content, 'html.parser').find('table')
for i in range(1,11):
print 'Collecting page %d' % i
# add end-point links
links += [a['href'] for a in bs('companies?page=%d' % i).findAll('a')]
for link in links:
print 'Processing %s' % link
name = bn(link)
data[name] = {}
for row in bs(link).findAll('tr'):
desc, cont = row.findAll('td')
data[name][desc.text.encode()] = cont.text.encode()
print json.dumps(data)