康奈尔抓取数据集

If you want to skip the HTML tag digging and get straight to scraping, here’s the gist. Note that the scraper tries to do an exact match with each item in your wanted list. Otherwise, read on for a short background on webscraping, when it’s useful to scrape websites, and some challenges you may experience while scraping.

如果您想跳过HTML标签的挖掘而直接进行抓取,请按以下要点进行。 请注意,搜寻器会尝试与所需列表中的每个项目进行完全匹配。 否则,请继续阅读有关网络抓取的简短背景,对抓取网站很有用的信息,以及在抓取时可能遇到的一些挑战。

from autoscraper import AutoScraper
# replace with desired url
url = 'https://www.yelp.com/biz/chun-yang-tea-flushing-new-york-flushing' 
# make sure that autoscraper can exactly match the items in your wanted_list 
wanted_list = ['A review']     # replace with item(s) of interest


# build the scraper
scraper = AutoScraper()
result = scraper.build(url, wanted_list)


# get similar results, and check which rules to keep
groups = scraper.get_result_similar(url, grouped=True)
groups.keys()
groups['rule_io6e'] # replace with rule(s) of interest


# keep rules and save the model to disk
scraper.keep_rules('rule_io6e') # replace with rule(s) of interest
scraper.save('yelp-reviews')    # replace with desired model name




#-------------------------------------------------------------------------
# using the model later
scraper.load('yelp-reviews')
new_url = ""                    # replace with desired url
scraper.get_result_similar(new_url)

背景 (Background)

I’ve recently been doing some research into bubble tea trends in the United States. I wanted to look at changes in drink orders, when boutique and franchise bubble tea shops were opened, and customer reviews regarding these establishments. Naturally, I turned to Yelp. But a few limitations very quickly set me back; I was limited to the first 1000 businesses on the Yelp API, and I could only get three Yelp selected reviews per business.

我最近一直在研究美国的泡泡茶趋势。 我想看一下饮料订单的变化,开设精品店和特许经营的泡茶店时的情况,以及有关这些场所的顾客评论。 自然,我转向Yelp。 但是一些限制很快使我退缩。 我仅限于Yelp API上的前1000家企业,每个企业只能获得3条Yelp选定的评论。

This makes sense from a business perspective — you wouldn’t want other businesses easily snooping in on your successes and failures and iterating off that. But it also demonstrates the larger misfortunes about web scraping. On one hand, it’s a great way to obtain data for a side project on a topic we’re interested in. On the other, companies rarely want bots interacting on their websites. Even if they offer APIs, they don’t always expose every piece of information needed.

从业务角度讲,这是有道理的-您不希望其他业务轻易窥探您的成功和失败并进行迭代。 但这也证明了有关网络抓取的更大不幸。 一方面,这是一种获取有关我们感兴趣的主题的副项目数据的好方法。另一方面,公司很少希望机器人在其网站上进行交互。 即使它们提供API,也不会总是公开所有需要的信息。

Security against webscraping has also increased. From header data verification, to CAPTCHA challenges, to machine-learning guided behavioral approaches, a lot of work has been invested to make it harder for bots to scourge websites. Lastly, most pages don’t immediately provide useful information in HTML. Instead, they are injected through JavaScript execution, and only when a “real user” has been detected.

防范网络爬虫的安全性也有所提高。 从头数据验证到验证码挑战,再到机器学习指导的行为方法,已经投入了大量的工作,以使机器人更难以发现网站。 最后,大多数页面不会立即以HTML提供有用的信息。 相反,只有通过检测到“真实用户”时,才通过JavaScript执行注入它们。

Hence the trusty process of:

因此,值得信赖的过程是:

  1. Manually navigating to a website

    手动导航到网站
  2. Highlight a segment of interest

    突出显示感兴趣的部分
  3. Right click and inspect elements

    右键单击并检查元素
  4. Copy the HTML tag or XPath, and use a library like BeautifulSoup to parse the html

    复制HTML标记或XPath,并使用BeautifulSoup之类的库来解析html

流程 (The Process)

Here’s an example from my project. Let’s say you wanted to parse reviews from Yelp on a particular bubble tea shop https://www.yelp.com/biz/chun-yang-tea-flushing-new-york-flushing?osq=bubble%20tea&sort_by=date_desc (I am not affiliated with this bubble tea shop, nor with Yelp. This is a sample from my current project on analyzing bubble tea trends in the United States.)

这是我的项目中的一个示例。 假设您想解析来自Yelp的特定泡泡茶店的评论https://www.yelp.com/biz/chun-yang-tea-flushing-new-york-flushing?osq=bubble%20tea&sort_by=date_desc(I既不隶属于这家泡泡茶店,也没有隶属于Yelp。这是我目前在分析美国泡泡茶趋势项目中的一个示例。)

You would first need to set up a headless browser, or emulate the header of a real browser, in order to execute any JavaScript on a dynamic webpage.

为了在动态网页上执行任何JavaScript,您首先需要设置无头浏览器或模拟真实浏览器的标题。

from selenium import webdriver


def setup_browser(driver_path=None, headless=False):
    op = webdriver.ChromeOptions()
    if headless:
        op.add_argument('headless')


    if driver_path:
        return ebdriver.Chrome(driver_path, options=op)
    # this depends on where you install chromedriver
    return webdriver.Chrome(r"C:\bin\chromedriver.exe", options=op) 
    
    
browser = setup_browser(headless=True)

Then, connect it to a library that can pull data out of HTML and XML files.

然后,将其连接到可以从HTML和XML文件中提取数据的库。

from bs4 import BeautifulSoup
url = "https://www.yelp.com/biz/chun-yang-tea-flushing-new-york-flushing?osq=bubble%20tea&sort_by=date_desc"
browser.get(url)


response = BeautifulSoup(browser.page_source, 'html.parser')
published = response.find_all('span', class_='lemon--span__373c0__3997G raw__373c0__3rKqk')

In order to figure out the specific tag, lemon--span__373c0__3997G raw__373c0__3rKqk, that would lead me to the reviews, I followed the numbered list of steps above, highlighting a sample review, inspecting the elements, and snooping around for the tag of interest.

为了弄清楚lemon--span__373c0__3997G raw__373c0__3rKqk这个标签,该标签将导致我进行评论,我按照上面列出的步骤编号,突出显示示例评论,检查元素并四处寻找感兴趣的标签。

问题 (The Problem)

This actually ends up being quite brittle, since websites may change how they render their pages at any time. More importantly, this process is redundant, in the sense that we need to first find the desired tags manually before we can set up an automated webscraper.

实际上,这最终变得非常脆弱,因为网站可能随时更改其呈现页面的方式。 更重要的是,此过程是多余的,因为从某种意义上说,我们需要先手动找到所需的标签,然后才能设置自动网络抓取工具。

另一种方法 (Another Approach)

Instead of searching for the HTML tag or the XPath, why not just automate the manual search using simple matching rules? This is the basic premise of the AutoScraper library by Alireza Mika. Let’s walk through the same task of scraping Yelp reviews, this time with the AutoScraper library.

为什么不使用简单的匹配规则自动执行手动搜索,而不是搜索HTML标记或XPath? 这是Alireza Mika创建的AutoScraper库的基本前提。 让我们通过AutoScraper库完成抓取Yelp评论的相同任务。

#0
from autoscraper import AutoScraper


#1
url = "https://www.yelp.com/biz/chun-yang-tea-flushing-new-york-flushing?osq=bubble%20tea&sort_by=date_desc"


#2
wanted_list = ['Tried their Brown Sugar milk tea and it was not bad compare to Tiger Sugar. I prefer this over Tiger Sugar due to the L size option and sweetness content. It was my to go bubble tea spot for the last two days straight. Will visit again!']


#3
scraper = AutoScraper()


#4
result = scraper.build(url, wanted_list)


print(result)

The AutoScraper object #3 takes in a target url #1 and a list of wanted items #2, and builds some rules around the provided parameters #4. Note that it’ll only mark tags that exactly match the items of interest; thus, the review I included in the the wanted_list is the first review on the Yelp webpage in its entirety.

AutoScraper对象#3接收目标URL#1和所需商品#2的列表,并围绕提供的参数#4构建一些规则。 请注意,它只会标记与感兴趣的项目完全匹配的标签; 因此,我包含在wanted_list中的评论是Yelp网页上的第一个评论。

Upon printing results, you’ll get to see all the elements that the webscraper has found. You can fetch these results again on the same or another url with the following command.

打印results ,您将看到该webscraper找到的所有元素。 您可以使用以下命令在相同或另一个URL上再次获取这些结果。

scraper.get_result_similar(url)

scraper.get_result_similar(url)

You may notice that the scraper has picked up on some extraneous pieces of information. You can fine-tune its selections by first grouping them under the rules that the scraper has learned:

您可能会注意到刮板已获取了一些无关的信息。 您可以通过首先按照刮板了解到的规则将它们分组来微调其选择:

groups = scraper.get_result_similar(url, grouped=True)

Since groups is a dictionary, you can get the names of the rules by calling print(groups.keys())

由于groups是字典,因此可以通过调用print(groups.keys())来获取规则的名称。

You can then key into the dictionary using a particular rule:

然后可以使用特定规则键入字典:

groups['rule_io6e']

groups['rule_io6e']

If the results of the specified rule accurately reflects the desired results, you can choose to keep the rule with the method call:

如果指定规则的结果准确地反映了所需的结果,则可以选择使用方法调用保留规则:

scraper.keep_rules('rule_io6e')

Lastly, you can persist the model to file for later use.

最后,您可以持久保存模型以备后用。

scraper.save('yelp-reviews')

收盘时 (In Closing)

Of course, this library is not foolproof. Click-intensive webpages, such as Google’s reviews of a business, would be rather challenging to automate without a browser emulator.

当然,这个库不是万无一失的。 点击密集型网页(例如Google的商家评论)在没有浏览器仿真器的情况下实现自动化将非常具有挑战性。

Since AutoScraper expects an exact match between items in the wanted list and items that appear on a website, it can be difficult to pinpoint a constantly updating value, such as the price of a stock.

由于AutoScraper期望所需列表中的项目与网站上显示的项目之间完全匹配,因此很难确定不断更新的价值,例如股票价格。

However, as developers, part of our responsibilities is to tie solutions along a pipeline together to iterate on or create a new product. Hopefully, you can make use of this scraping library, whether in a framework like scrapy, or just to simplify your next scraping task.

但是,作为开发人员,我们的部分职责是将解决方案沿管道捆绑在一起以迭代或创建新产品。 希望您可以在scrapy之类的框架中使用此抓取库,或者只是为了简化下一个抓取任务。

Regardless of how you decide to scrape a website, do so responsibly!

无论您决定如何抓取网站,都应负责任地这样做!

  1. Don’t bombard a website with requests. This is the number one mistake people new to webscraping do: they try to speed up scraping by sending multiple requests at a time, from multiple servers — this is a DDoS attack!

    不要用请求轰炸一个网站 。 这是网络爬虫新手遇到的第一个错误:他们试图通过一次从多个服务器发送多个请求来加快爬网速度,这是DDoS攻击!

  2. Respect the robots.txt: you can usually find them by adding robots.txt to the index page. For example, https://www.yelp.com/robots.txt

    尊重robots.txt:通常可以通过将robots.txt添加到索引页面来找到它们。 例如, https://www.yelp.com/robots.txt

  3. Use the provided API!

    使用提供的API!

翻译自: https://towardsdatascience.com/a-quicker-way-to-build-datasets-through-web-scraping-4ce9e51e16d8

康奈尔抓取数据集

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐