【问题标题】:Periodic web scraping to scrape new information on the website since the last time it ran自上次运行以来,定期网络抓取以抓取网站上的新信息
【发布时间】:2019-06-16 17:49:56
【问题描述】:

我正在抓取这个网站:https://news.ycombinator.com/jobs。我有抓取网站并将所需信息存储在本地数据库中的代码。我需要抓取的信息是:

  1. 正在招聘的公司的名称。
  2. 公司的位置。
  3. 广告的位置。

我的问题是:如何改进我的脚本以执行以下任务?

  1. 定期抓取网站。
  2. 抓取工具应该只抓取网站上自上次以来的新信息 运行时间。
import mysql.connector
from mysql.connector import errorcode
from bs4 import BeautifulSoup
import requests

url = "https://news.ycombinator.com/jobs"
response = requests.get(url, timeout=5)
content = BeautifulSoup(response.content, "html.parser")

table = content.find("table", attrs={"class":"itemlist"})

array = []
for elem in table.findAll("a", attrs={"class":"storylink"}):
    array.append(elem.text)

try:
    # open the database connection
    cnx = mysql.connector.connect(user='root', password='mypassword',
                                  host='localhost', database='scraping')
    insert_sql = ('INSERT INTO `jobs` (`listing`) VALUES (%s)')

    # get listing data
    listing_data = array

    # loop through all listings executing INSERT for each with the cursor
    cursor = cnx.cursor()
    for listing in listing_data:
        print('Storing data for %s' % (listing))
        cursor.execute(insert_sql, (listing,))

    # commit the new records
    cnx.commit()

    # close the cursor and connection
    cursor.close()
    cnx.close()

except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print('Something is wrong with your username or password')
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print('Database does not exist')
    else:
        print(err)

else:
    cnx.close()

【问题讨论】:

    标签: mysql python-3.x web-scraping beautifulsoup python-requests


    【解决方案1】:

    1) 您可以设置一个 cron 作业以使该脚本定期运行。

    2) 你在 DOM 中还遗漏了一些东西:

    <tr class="athing" id="20190856">
          <td align="right" valign="top" class="title"><span class="rank"></span></td>      <td></td><td class="title">...
    

    每个职位发布都有一个唯一的 ID(根据 HN API 文档:https://github.com/HackerNews/API),因此只需抓取此 ID 并确保您的数据库中还没有它。

    您也可以只使用 API 而不是抓取 HTML!

    【讨论】:

    • 我的第一部分正在工作,我在 Windows 上,所以我使用了任务计划程序。关于第二部分,告诉我我是否走上正轨。我需要首先获取我的数据库中已经存在的所有 id(如果 id 存在),而不是比较抓取项目的 id,如果 id 是新的,则将其插入数据库,否则忽略它。对吗?
    • 是的,这就是你应该做的!您还可以使用像 SqlAlchemy 这样的 ORM 来简化操作,而不必自己编写 SQL 查询。
    • 这个解决方案对于这个小规模的项目来说似乎没问题。如果这是一个大型项目,我必须一次刮掉几千件物品,你有什么建议。很快我的数据库将有数百万条记录,我必须与这些记录进行比较。有没有办法只在网络上抓取新信息而不比较项目 ID 和数据库项目 ID?
    • 您可以将此 ID 作为主键并让您的数据库检查它是否已存在。主键本质上是索引的,所以无论您有几百万条记录都没有关系!
    • 有道理。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多