我正在尝试从链接中抓取表格。因此,需要从中抓取“ href”链接,然后尝试从中抓取表。我尝试执行以下代码,但找不到:
from bs4 import BeautifulSoup
import requests
url = 'http://www.stats.gov.cn/was5/web/search?channelid=288041&andsen=%E6%B5%81%E9%80%9A%E9%A2%86%E5%9F%9F%E9%87%8D%E8%A6%81%E7%94%9F%E4%BA%A7%E8%B5%84%E6%96%99%E5%B8%82%E5%9C%BA%E4%BB%B7%E6%A0%BC%E5%8F%98%E5%8A%A8%E6%83%85%E5%86%B5'
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
#table = soup.find("table")
#print(table)
# links = []
# for href in soup.find_all(class_='searchresulttitle'):
# print(href)
# links.append(href.find('a').get('href'))
# print(links)
link = soup.find(attr={"class":"searchresulttitle"})
print(link)
所以请指导我如何找到他们的href和刮擦表
答案 0 :(得分:1)
URL在Javascript中作为变量存储在HTML中。 BeautifulSoup可用于获取所有<script>
元素,然后可使用正则表达式提取urlstr
的值。
假设正在使用Python 3.6,可以使用字典来创建显示的URL的唯一ordred列表:
from bs4 import BeautifulSoup
import requests
import re
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'}
url = 'http://www.stats.gov.cn/was5/web/search?channelid=288041&andsen=%E6%B5%81%E9%80%9A%E9%A2%86%E5%9F%9F%E9%87%8D%E8%A6%81%E7%94%9F%E4%BA%A7%E8%B5%84%E6%96%99%E5%B8%82%E5%9C%BA%E4%BB%B7%E6%A0%BC%E5%8F%98%E5%8A%A8%E6%83%85%E5%86%B5'
r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.content, 'html.parser')
urls = {} # Use a dictionary to create unique, ordered URLs (Assuming Python >=3.6)
for script in soup.find_all('script'):
for m in re.findall(r"var urlstr = '(.*?)';", script.text):
urls[m] = None
urls = list(urls.keys())
print(urls)
这将显示以以下内容开头的URL:
['http://www.stats.gov.cn/tjsj/zxfb/201811/t20181105_1631364.html',
'http://www.stats.gov.cn/tjsj/zxfb/201810/t20181024_1629464.html',
'http://www.stats.gov.cn/tjsj/zxfb/201810/t20181015_1627579.html',
...]