【问题标题】:Web Scraping: How do I get 'href' links and scrape table from themWeb Scraping:如何获取“href”链接并从中获取表格
【发布时间】:2018-11-05 05:10:39
【问题描述】:

我正在尝试从链接中抓取表格。因此需要从中刮取“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和scrape table

【问题讨论】:

  • 你最好使用selenium之类的东西来获取这个网页的源代码并用漂亮的汤来解析它
  • 我没用硒,你能告诉我不要喝漂亮的汤吗
  • 查看汤输出它没有您需要的表格,因为它仅包含静态 html 内容而不包含动态 html 内容,该表格是由 javascript 动态生成的,要获取该源代码,您必须渲染网页和得到桌子。呈现网页的方式有很多种,其中一种是使用selenium
  • 能否分享一下代码或者如何获取href
  • 我没有写任何代码,我给你一个链接跟随sentdexbeautifulsouptutorial

标签: python web-scraping beautifulsoup request


【解决方案1】:

URL 作为 Javascript 中的变量存储在 HTML 中。 BeautifulSoup 可用于获取所有<script> 元素,然后可以使用正则表达式提取urlstr 的值。

假设使用的是 Python 3.6,则可以使用字典来创建显示的 URL 的唯一排序列表:

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', 
...]

【讨论】:

    猜你喜欢
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    相关资源
    最近更新 更多