detail.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import json
  2. import time
  3. import copy
  4. from commons.Logger import logger
  5. from commons.conn_mysql import MySQLPoolOnline
  6. from spiders.taobao.taobao_login import (TaobaoAutoCrawl)
  7. db_online = MySQLPoolOnline()
  8. sql = "SELECT *,SUBSTRING_INDEX(platform_item_id, '+', 1) AS pre_id FROM retrieve_scrape_data WHERE scrape_date = '2026-06-13' and enterprise_id=11 and platform_item_id LIKE '%+%' group by pre_id ;"
  9. data_list =db_online.select_data(sql,)
  10. print(data_list)
  11. taobao_auto = TaobaoAutoCrawl('1', {}, 'n')
  12. driver = taobao_auto.run()
  13. for i in data_list:
  14. url = i.get('link_url')
  15. driver.get(url)
  16. try:
  17. target = driver.eles('xpath://*[@class="content--DIGuLqdf"]')[-1]
  18. title_list = target.eles('xpath://span')
  19. title_list[-1].click()
  20. time.sleep(1)
  21. new_data = []
  22. for j in title_list:
  23. j.click()
  24. new_price = (driver.eles('xpath://*[@class="block2--MLcO9YdF"]//*[@class="text--LP7Wf49z"]'))[0].text
  25. new_url = driver.url
  26. new_title = j.text
  27. data = copy.copy(i)
  28. data.update({'product_name': new_title, 'min_price': new_price, 'link_url': new_url})
  29. new_data.append(data)
  30. time.sleep(2)
  31. except Exception as e:
  32. logger.exception("页面操作失败, url=%s: %s", url, e)
  33. continue
  34. if not new_data:
  35. continue
  36. pre_id = data.get('pre_id')
  37. db_online.execute("START TRANSACTION")
  38. try:
  39. if not pre_id:
  40. logger.warning('pre_id 为空,跳过删除')
  41. else:
  42. delete_sql = "DELETE FROM retrieve_scrape_data WHERE platform_item_id LIKE %s AND scrape_date = %s"
  43. db_online.execute(delete_sql, (f'{pre_id}%', '2026-06-13'))
  44. table_name = "retrieve_scrape_data"
  45. for product in new_data:
  46. del product['pre_id']
  47. del product['id']
  48. cols = list(product.keys())
  49. placeholders = ["%s"] * len(cols)
  50. sql = f"""
  51. INSERT INTO `{table_name}` ({','.join([f'`{c}`' for c in cols])})
  52. VALUES ({','.join(placeholders)})
  53. """
  54. db_online.execute(sql, list(product.values()))
  55. logger.info("%s", json.dumps(product, ensure_ascii=False, default=str))
  56. db_online.execute("COMMIT")
  57. logger.info("写入 %d 条, pre_id=%s", len(new_data), pre_id)
  58. except Exception as e:
  59. db_online.execute("ROLLBACK")
  60. logger.exception("事务回滚, pre_id=%s: %s", pre_id, e)
  61. driver.quit()