2017.07.20

scrapy 爬虫,能够将知乎上的问题和答案爬取并入库

item, itemloader, mysqldb

使用 twisted 异步框架,MySQLdb 入库时,构造的sql语句
cursor.execute(insert_sql, params)的时候,不管参数是什么类型,都只能使用 %s,不然会报错

比如:
insert_sql = "insert into tb_name values(%s, %s, %s, %s)"
params = (pram1, pram2, pram3, pram4)
不管 params 元组中的数据元素是什么类型的数据,在 insert_sql 中都只能使用 %s,不然就会报出 sql 语句的错误

在文档中查找(http://mysql-python.sourceforge.net/MySQLdb.html#cursor-objects)

     c=db.cursor()
     max_price=5
     c.execute("""SELECT spam, eggs, sausage FROM breakfast
      WHERE price < %s""", (max_price,))

In this example, max_price=5 Why, then, use %s in the string? Because MySQLdb will convert it to a SQL literal value, which is the string '5'. When it's finished, the query will actually say, "...WHERE price < 5".

Why the tuple? Because the DB API requires you to pass in any parameters as a sequence. Due to the design of the parser, (max_price) is interpreted as using algebraic grouping and simply as max_price and not a tuple. Adding a comma, i.e. (max_price,) forces it to make a tuple.

The only other method you are very likely to use is when you have to do a multi-row insert:

  c.executemany(
  """INSERT INTO breakfast (name, spam, eggs, sausage, price)
  VALUES (%s, %s, %s, %s, %s)""",
  [
  ("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ),
  ("Not So Much Spam Plate", 3, 2, 0, 3.95 ),
  ("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95 )
  ] )

Here we are inserting three rows of five values. Notice that there is a mix of types (strings, ints, floats) though we still only use %s. And also note that we only included format strings for one row. MySQLdb picks those out and duplicates them for each row.


知乎存在反爬虫策略,即每间隔一段时间就会对 User-Agent 进行检验,程序自动爬虫的时候,就会发现,后面的 http 请求的返回码都是 403,打开这个请求的连接,发现知乎需要你输入验证码通过后才能继续进入。

后续在处理这个爬虫策略的问题

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 我们长大了! 此刻我们成为… 成为北京桑迪艾扬格瑜伽中心! 这是一份没有期限的邀请 我们有专业的教师和教室 我们准...
    牛牛童鞋阅读 1,339评论 0 0
  • 做作业的时候遇到的,昨天晚上折腾到一点多才找出来的bug,虽然想想是很弱智的问题,主要是定位花了一点时间; 这段代...
    陌路晨曦阅读 1,651评论 0 0
  • 四方天井,一碗星星。薄云飘过,影落心中。 ——大理想国-...
    自在悠游阅读 1,950评论 0 1
  • 一、千层系列(6寸) ①4寸盒子榴莲千层 ②榴莲千层 ③芒果千层 ④彩虹千层 ⑤榴莲芒果双拼 ⑥抹茶奥利奥千层 ⑦...
    ANGELIA小九阅读 3,269评论 0 0
  • 曾经那些时光,美好的时光都已随风而逝了吗,对童年的怀念如同梦境,时光不重现,你也不可能飞过时间那堵墙。 有时候,我...
    追天青年阅读 1,716评论 0 0