【发布时间】:2019-06-16 17:49:56
【问题描述】:
我正在抓取这个网站:https://news.ycombinator.com/jobs。我有抓取网站并将所需信息存储在本地数据库中的代码。我需要抓取的信息是:
- 正在招聘的公司的名称。
- 公司的位置。
- 广告的位置。
我的问题是:如何改进我的脚本以执行以下任务?
- 定期抓取网站。
- 抓取工具应该只抓取网站上自上次以来的新信息 运行时间。
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