【发布时间】:2019-09-07 20:00:07
【问题描述】:
我在 python 中创建了一个脚本来从网站上获取不同帖子的标题,它可以完美地抓取它们。
但是,我现在希望这个脚本做的是记住最后一次抓取的结果,这样当我运行它两次时,它就不会获取相同的结果。更清楚一点 - 脚本将在第一次执行时像往常一样解析结果,但在没有找到新帖子之前,它不会在后续执行中获取相同的结果。
使用 csv:
import csv
import requests
from bs4 import BeautifulSoup
def get_posts(url):
response = requests.get(url)
soup = BeautifulSoup(response.text,"lxml")
for item in soup.select(".summary .question-hyperlink"):
yield item.text
if __name__ == '__main__':
link = 'https://stackoverflow.com/questions/tagged/web-scraping'
with open("output.csv","w",newline="") as f:
writer = csv.writer(f)
for item in get_posts(link):
writer.writerow([item])
print(item)
使用数据库:
import mysql.connector
from bs4 import BeautifulSoup
import requests
url = "https://stackoverflow.com/questions/tagged/web-scraping"
def connect():
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd = "",
database="mydatabase"
)
return mydb
def create_table(link):
conn = connect()
mycursor = conn.cursor()
mycursor.execute("DROP TABLE if exists webdata")
mycursor.execute("CREATE TABLE if not exists webdata (name VARCHAR(255))")
response = requests.get(link)
soup = BeautifulSoup(response.text,"lxml")
for items in soup.select(".summary"):
name = items.select_one(".question-hyperlink").get_text(strip=True)
mycursor.execute("INSERT INTO webdata (name) VALUES (%s)",(name,))
conn.commit()
def fetch_data():
conn = connect()
mycursor = conn.cursor()
mycursor.execute("SELECT * FROM webdata")
for item in mycursor.fetchall():
print(item)
if __name__ == '__main__':
create_table(url)
fetch_data()
上述脚本每次运行时都会解析相同的结果。
如何让我的脚本记住上次抓取的结果,以便在后续执行中不会再次抓取相同的结果?
【问题讨论】:
-
将结果存储在 db 或 .txt 文件中?
-
记住最后的抓取 URL 怎么样?如果脚本采用此 Url - 中断。
-
无论如何您都必须进行刮擦和比较,那么为什么不简单地重新覆盖/写入呢? SO 结果会转移页面,因此无论如何您都必须检查每个链接。
-
当答案简单时,不费吹灰之力的问题仍然可能得到有用的答案。您要问的问题很复杂,而且您的问题给人的印象(可能是错误的)是您没有做出足够的努力来理解没有简单的方法可以实现您想要实现的目标。这不仅仅是有点棘手。
标签: python python-3.x web-scraping beautifulsoup