gpt4 book ai didi

mysql - 定期进行网络抓取,以抓取自上次运行以来网站上的新信息

转载 作者:行者123 更新时间:2023-11-29 09:41:01 24 4
gpt4 key购买 nike

我正在抓取这个网站: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()

最佳答案

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!

关于mysql - 定期进行网络抓取,以抓取自上次运行以来网站上的新信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56621289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com